1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { readAllSync } from "https://deno.land/std@0.141.0/streams/conversion.ts";
import { screenshotPage } from "https://esm.town/v/charlypoly/browserbaseUtils";
import { blob } from "https://esm.town/v/std/blob";
import { Buffer } from "node:buffer";
import pixelmatch from "npm:pixelmatch";
import { PNG } from "npm:pngjs";
import slugify from "npm:slugify";
export async function hasWebsiteChanged(url: string, threshold = 0.5) {
const slug = slugify(url);
const buffer = await screenshotPage(url);
const previousScreenshots = await blob.list(`${slug}_`);
await blob.set(`${slug}_${+(new Date())}`, buffer);
if (!previousScreenshots[0]) {
return false;
}
const previous = await blob.get(previousScreenshots[previousScreenshots.length - 1].key);
for (let i = 0; i < previousScreenshots.length; i++) {
await blob.delete(previousScreenshots[i].key);
}
const previousBuffer = await previous.arrayBuffer();
const img1Buf = Buffer.from(buffer.buffer);
const img2Buf = Buffer.from(previousBuffer);
const previousImage = PNG.sync.read(img1Buf);
const currentImage = PNG.sync.read(img2Buf);
try {
const result = pixelmatch(previousImage.data, currentImage.data, null, previousImage.width, previousImage.height, {
threshold,
});
return result > 0;
} catch (e) {
console.error(e);
}
return false;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
June 13, 2024