A before and after screenshot diff in headless Chrome, with no npm packages
I build Framer templates and check them with a small tool that loads every page in headless Chrome at several widths. Text styles in Framer are shared, so a fix to one style touches every layer that uses it, on every bre
I build Framer templates and check them with a small tool that loads every page in headless Chrome at several widths. Text styles in Framer are shared, so a fix to one style touches every layer that uses it, on every breakpoint, including the ones I'm not looking at.
I wanted to see everything that changed between two runs, not only the thing I meant to fix. The usual answer is Puppeteer or Playwright plus an image diff library. My tool has no npm dependencies (Node 22 and an installed Chrome), and I wanted to keep it that way. It turned out Chrome could do every part of the job itself.
Talking to Chrome without Puppeteer
Node 22 has a global WebSocket, which is all you need for the Chrome DevTools Protocol. Start Chrome with a throwaway profile and port 0, so it picks a free port:
const proc = spawn(chromePath, [
"--headless=new",
"--remote-debugging-port=0",
`--user-data-dir=${profileDir}`,
"about:blank",
])
Chrome writes the port it chose to a DevToolsActivePort file inside the profile folder. Read it, ask /json/list for the page's WebSocket address, and connect:
const port = readFileSync(join(profileDir, "DevToolsActivePort"), "utf8").split("\n")[0]
const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()
const ws = new WebSocket(targets.find((t) => t.type === "page").webSocketDebuggerUrl)
After that, every command is a JSON message with an id, and the reply comes back with the same id:
let nextId = 1
const pending = new Map()
ws.addEventListener("message", (e) => {
const m = JSON.parse(e.data)
if (pending.has(m.id)) {
pending.get(m.id)(m.result)
pending.delete(m.id)
}
})
const send = (method, params = {}) =>
new Promise((resolve) => {
const id = nextId++
pending.set(id, resolve)
ws.send(JSON.stringify({ id, method, params }))
})
My real driver also handles errors and timeouts, but that's the core. Runtime.evaluate runs code in the page, and Page.captureScreenshot with a clip takes a picture of any part of it.
Freezing the page first
Two screenshots of the same page are rarely identical. Animations, transitions, videos and the text cursor all move between shots. Before taking any pictures, I run this in the page:
const style = document.createElement("style")
style.textContent = "*, *::before, *::after { transition: none !important; caret-color: transparent !important; }"
document.head.appendChild(style)
for (const a of document.getAnimations()) {
if (a.effect.getTiming().iterations === Infinity) {
a.pause()
a.currentTime = 0 // endless loops stop at their start
} else {
a.finish() // one-off entrances jump to their end
}
}
for (const v of document.querySelectorAll("video")) {
v.pause()
v.currentTime = 0
}
document.getAnimations() returns CSS animations, CSS transitions and Web Animations in one list, which covers a lot of what a Framer site animates. The next step catches what it misses. Afterwards the tool restarts exactly what it paused, so anything that runs later sees the page as it was.
Then take every screen twice
Some motion is driven by scripts, like a ticker that updates on requestAnimationFrame, and freezing doesn't reach it. So the tool scrolls down the page one screen at a time, takes a shot of each, waits about a second, and does it all again. If a screen changed between the two passes, nothing I did caused that, so those areas are ignored when the two runs are compared.
Text that changes by itself, like a clock or a countdown, gets the same treatment: the tool records each element's text before and after the two passes, and any element whose text changed on its own is left out of the comparison.
Chrome as the image library
Comparing the images is where I expected to need a package. I didn't. A blank headless page has createImageBitmap, OffscreenCanvas and getImageData, which is everything a pixel diff needs:
async function load(url) {
const bitmap = await createImageBitmap(await (await fetch(url)).blob())
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)
const ctx = canvas.getContext("2d")
ctx.drawImage(bitmap, 0, 0)
return { w: bitmap.width, h: bitmap.height, data: ctx.getImageData(0, 0, bitmap.width, bitmap.height).data }
}
Node reads the two JPEGs from disk, passes them in as data URLs through Runtime.evaluate, and the page compares them.
The comparison works on a grid of small square cells rather than single pixels. A cell counts as changed when enough of its pixels moved by more than a small amount on any color channel. That ignores JPEG noise and anti-aliasing, which would otherwise light up every edge on the page. Changed cells that sit close together are grouped into boxes, and each box becomes a before and after crop, with the changed area outlined on the after side, drawn with the same OffscreenCanvas and saved with convertToBlob.
Three things that tripped me up
The last screen overlaps. Scrolling stops at the bottom of the page, so the last screenshot repeats part of the one before it. My first version listed one changed date twice. Now anything the previous screen already covered is dropped.
A page that changes height moves everything below it. If a fix adds a line of text near the top, every pixel below shifts, and the diff calls the whole rest of the page changed. When the page height differs between runs, the report shows only the first change and says to check the rest by eye.
Both runs need the same setup. Fonts render slightly differently across machines and Chrome versions. The two runs have to use the same pages, the same widths, the same computer and the same Chrome, or the diff is mostly noise.
What it gives me
After a fix, I run the checker again and get a report of every page and width that looks different, each with a before and after close-up. A change isn't a bug, so nothing here counts as a finding. I use it to confirm that a fix changed only what I meant to change.
The checker this lives in is Template QA, which tests live Framer sites.
Do you run visual diffs on your own sites? What do you use to keep animations from showing up as changes?
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.