Page snapshots and heatmaps
How the module negotiates, checks and stores page snapshots, what it accepts as residual risk, and how clicks are anchored to elements and drawn over a snapshot.
A heatmap needs the page it was clicked on, and most production sites refuse to be framed. The module therefore captures a masked, static snapshot of the page in the visitor's browser and draws the clicks over it. This page explains the snapshot contract and how clicks find their element again.
Snapshot contract
Two public routes carry snapshots. Both check the browser origin and declared automation like collect does. Only the upload also applies a per-source rate budget.
Negotiation with GET snapshot.js
GET snapshot.js?website=&path=&width=[&root=1] answers the capture script from static/snapshot/ when the backend wants a capture of that website, path and layout. The script is prefixed with window.__dmsMarketingSnapshotConfig, which holds the site's maskText, the byte cap and a one-time token. In every other case the route answers an empty script, because a page has nothing to do with a reason. A request with neither Origin nor Referer passes this route's origin check.
The backend wants a capture when all three hold:
- the site opted in
- no capture younger than
SNAPSHOT_REFRESH_AGE_MS(a day) exists - no other visitor received the capture script for that key within
SNAPSHOT_PROMISE_TTL_MS(a minute)
Both facts live in bounded caches on each instance (services/snapshots.ts), backed by one key lookup on a miss. A busy page therefore costs the database almost nothing between captures. An instance trusts what it read of a row for SNAPSHOT_CAPTURE_CACHE_TTL_MS (5 minutes), never for the refresh age that the row gates. A page left without a snapshot is captured at its next sampled visit, whatever removed the snapshot.
A deletion through deleteSnapshots clears the instance's cache at once. That covers an option change, a heatmap reset of the page or the site, and a removed website. The retention prune clears it too. Another instance, or a row deleted by hand, is noticed within the TTL. A refused upload records no capture time, so the key waits at most until its promise expires, a minute later.
root=1 means the tracker sees the page scroll an inner container. A capture stored before captures recorded their scroll-root mark, so a row without a scrollRoot field, is then stale and replaced at once. A capture that recorded the mark is not, whether it found a root or not. A page that the two scripts disagree on is therefore not captured on every visit.
The route answers with Cache-Control: private, no-store, because the answer is a decision, not a file.
Upload with POST snapshot
The capture posts the serialized document as text/plain JSON, with no preflight, like collect. It gzips the body when the browser has CompressionStream. A no-cors request cannot send Content-Encoding, so the server detects gzip from the body's magic bytes (inflateIfGzipped).
The upload passes these checks in order:
@RawBodyreads the body under a hard cap,MAX_SNAPSHOT_MAX_BYTES(8 MiB), the highest valuesnapshotMaxBytescan take. It refuses a declared length past the cap before it reads a byte, and cuts an undeclared one the moment it crosses the cap, with 413.- The configured
snapshotMaxBytes(1 MiB by default) applies to the body as received, with 413 past it. A gzipped body inflates underMAX_SNAPSHOT_INFLATED_BYTES(32 MiB), with 413 past it. - zod validates the body.
- An unknown website, or a site whose tracking is off, answers 404.
- The origin gate answers 403 for an undeclared host. Unlike collect, a request with neither
OriginnorRefereris refused, because the capture'sfetchalways sends one. - The bot filter, and a budget of
MAX_SNAPSHOTS_PER_WINDOW_PER_SOURCE(3) uploads a minute per website and IP. - The page URL's host must be one that the site declares, because the console's Open link uses the stored origin.
- The negotiation itself. The upload must return the token that was handed out for that website, path and layout to the same visitor (the same anonymous hash). That visitor's open session must sit on that path, as its last pageview, which the tracker sends before it negotiates. The token is spent on use.
- A site holds at most
MAX_SNAPSHOTS_PER_WEBSITE(1000) captures. The cap blocks a new key only. Replacing an existing key is allowed.
Refusals after the origin gate answer 200 with accepted: false.
The server does not trust the document. It strips scripts, frames, plugins, event handlers, script URLs and form values again. It drops any <style> whose text holds a < that could open markup, meaning a < before a letter, !, / or ?. The capture writes the character after such a < as a CSS escape, so no real stylesheet is dropped, and a bare < such as @media (width < 48rem) stays. The server then puts a Content-Security-Policy meta in front (script-src 'none'; object-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'), on top of the console's script-less sandbox.
The row's ID is the hash of the website, layout and path, so each key has one row, replaced in place. The document is stored gzipped and base64-encoded, about 4/3 of the compressed upload. An 8 MiB upload stays near 11 MiB, under MongoDB's 16 MiB document limit. A document past MAX_STORED_SNAPSHOT_CHARS (12 MiB) is stored as an oversize report instead. Storage stays compressed, because the console reads and inflates one row at a time while the table holds up to 1000 rows per site.
The body has one of two shapes. The first is the capture. The second is oversizeBytes, the size the upload would have had, sent when serializing the page went past the cap in the visitor's browser. The second shape writes the same row with an empty document and a zero box, a weight instead of a rendering. It carries no document box on purpose. A page heavy enough to pass the byte cap often also exceeds MAX_SNAPSHOT_DOCUMENT_PX, and requiring a box would refuse the very reports this shape exists for.
What the browser captures
The tracker asks for a capture only on visits already sampled for clicks, since a backdrop is for pages with clicks. It asks after load, after a grace period and in idle time. The capture script waits for the DOM to stop changing before it serializes. It leaves out the transient overlays the visit had open (isTransientOverlay in static/snapshot/): the top layer, floating dialog, menu, listbox and tooltip roles, fixed live regions and toast viewports. It reads the computed position only for elements whose role or aria-live makes them candidates, so the rule costs almost nothing on a large page.
Pages and heatmaps lists what is always masked, the integrator markers and the size cap. Heatmap anchoring covers the rendering side.
While the site has snapshots on, the pages list (GET /stats/pages) adds a snapshot summary per path and the site's snapshotsEnabled. The summary holds the newest capture time, the layouts that hold a document, and tooHeavy when only oversize reports exist. It comes from one read of the site's captures without their documents (listCaptures, a pluck over the websiteId index). That read returns at most MAX_SNAPSHOTS_PER_WEBSITE small rows, never one read per path.
Residual risks the design accepts
A promise is per instance. Two instances may each hand the capture script to a visitor for one key within the same minute, and the second upload replaces the first. At worst that is one extra upload per instance per key per day. An upload that a load balancer sends to another instance than its negotiation finds no token and is refused. The next sampled visit captures instead.
A determined forger can still replace a backdrop. A script that sends a pageview, negotiates and uploads from one address with browser headers gets through, as a forged beacon does. What it gains is bounded: a page on the site's own hosts, once a day per key, inert and without form values. Reset in the console removes it.
A page too heavy to capture says so, once. Without the oversize report, such a page left no row. wantsSnapshot then picked another visitor to serialize it a minute later, forever, and the console could not tell it from a page never visited. The report row holds the key for a refresh age like any capture, so the retry is daily and the console can show the weight. It costs one of the site's 1000 slots. If the page grows past the cap between two captures, an oversize report replaces the backdrop, and the next capture under the cap takes it back.
A forged capture is a forged page. A scripted client with a browser user agent and a matching Origin can upload any document for a path of a site that opted in, within the caps. It can also claim a weight the page never had, up to MAX_REPORTED_SNAPSHOT_BYTES, and remove that path's backdrop until a real capture replaces it. The document renders inert, since the console frame runs no script, submits no form and navigates nowhere. The remedy is the same as for forged events, detection and the per-site purge. The heatmap reset deletes snapshots too.
Retention is bounded by the raw events. Whatever snapshotRetention says, the prune uses the shorter of it and rawEventsRetention. A backdrop that outlives every click it could back is content kept for nothing.
Heatmap anchoring
A click belongs to an element, not to a rectangle. A document fraction is not a property of the page. It divides by the document box, and on a page shorter than the visitor's window that box is the window. The same button then arrives with a different dy from every window size. That misplaces it under the overlay and spreads one point of interest over as many cells as there were window heights. Each click therefore also stores where it landed inside the element it hit (selector, ox, oy and nth). The overlay projects from that anchor, and the rollup buckets on it.
Resolving a selector needs the rendered page, and the rendered page is the snapshot. The console runs querySelectorAll against the snapshot document itself, with no round trip. Whenever that fails (no snapshot yet, the element is gone, or the selector is now ambiguous), the click falls back to dx and dy. Clicks captured before anchoring existed only have that fallback. Blocked elements keep their ID and class for this reason, so a click on a masked widget still resolves to the widget's box.
The fallback is counted, not hidden
After each measurement, the console asks the snapshot which requested anchors have no element at all (no nth match, or a selector it cannot parse, missingAnchors). It weighs the clicks behind them against all anchored clicks (utils/anchor-drift.ts). From DRIFT_MIN_SHARE (10 %) and DRIFT_MIN_CLICKS (5), it says that the page probably changed since the capture.
An element that exists but has no box at the width on screen is not missing. Clicks of every layout are drawn over one capture, and a phone-only menu sits undrawn in the desktop document. A responsive page that renders different elements per layout can still read as changed on another layout's snapshot. Switching the layout tells the two cases apart.
The rollup caps anchored cells at MAX_ANCHORED_HEATMAP_CELLS (2000) and moves the least-clicked ones into the document grid. Selectors are only as stable as the page's class names. A build that hashes class names would otherwise create a new set per deploy until the response grew without bound. The document grid needs no cap, because its 50 by 50 cells bound it.
The snapshot frame
The console renders the snapshot's HTML in an <iframe srcdoc sandbox="allow-same-origin">. Same-origin lets the console read the document's scrollWidth and scrollHeight and every anchor box directly (frontend-vue/app/composables/useSnapshotFrame.ts), with no message protocol and no timeout. Nothing else is allowed, so a document that arrived through a public endpoint runs no script, submits no form and navigates nowhere. pointer-events: none keeps the admin's clicks out.
The frame's size still comes from one reading at most, and the frame stays pinned at the captured viewport height until then (frontend-vue/app/build/composables/usePreviewFrame.ts). Sizing the frame from a reading taken through it runs away, with every 100vh section growing one step at a time. The document can fix what a live frame cannot. Before rendering, the console rewrites the viewport-relative units of the inlined stylesheets and inline styles (vh, svh, lvh, dvh, vmin and vmax, in declaration values only, because a Tailwind arbitrary value also puts 100vh in the selector). They become the pixels they had in the visitor's viewport (frontend-vue/app/utils/snapshotViewportUnits.ts). The one reading is then the visitor's page height, and the resize changes nothing inside.
Width matters as much as height, because click coordinates are fractions of the document's scrollWidth, not of the frame. The frame's color-scheme follows the visitor's mode at capture, so the page's media queries resolve as they did for the visitor.
Why a snapshot and not the live page
Framing the live site works only on sites that allow it. Production defaults (X-Frame-Options and the CSP frame-ancestors directive) refuse it without any signal the console can read. A snapshot is what the visitor saw, on any site, whatever rendered it.
The layout question remains. The module keeps one capture per website, path and layout, with the visitor's viewport bucketed into the console's three layouts (desktop, tablet and phone, in types/snapshots.ts). When the requested layout has no capture, the nearest one is reflowed. Open in a new tab targets the origin recorded with the capture. Nothing is inferred from domain, which holds only the apex host without a scheme.
Overlay switching
The click and scroll-depth overlays switch above one persistent iframe, through a segmented control in PagePreview.vue. A declarative Tab block would unmount hidden slots by default, which would tear down the frame and measure it again on every switch. Later overlays, such as a per-selector view, join the same control. The Most clicked list and the count pins read the same anchored cells that the overlay draws, resolved against the same frame, so they need no read of their own.
Scroll depth
A scroll event stores the maximum depth reached per sampled view, as an integer percentage of the visitor's scrollable range. The tracker sends it on leave and on SPA navigation. A sampled view that never scrolls reports 0, and a page that fits its viewport reports 100.
The read (GET /api/marketing/stats/scroll, services/heatmap.ts) reports a cumulative reached-at-depth distribution over measured views, not over all traffic. Older events recorded only views that scrolled, so historical windows can have a different denominator.
The overlay (frontend-vue/app/components/ScrollDepthOverlay.vue) anchors depth 0 at the bottom of the probe viewport. The visitors' real viewports are unknown here, so the gradient claims bands, not pixels. It draws in the pane's scaled space, where depth varies only vertically and labels keep their font size at every zoom. Resetting a heatmap deletes clicks, scroll depths and the matching page snapshots together (DELETE /api/marketing/stats/heatmap).
Pages that scroll an inner container
Everything above assumes that the document scrolls. An app shell scrolls an inner container instead, and its document is exactly the window. When the document does not scroll, findScrollRoot() in static/tracker/ returns that container. It picks the element marked data-marketing-scroll-root. Otherwise it picks the largest element with overflow-y set to auto or scroll and hidden content, found under five probe points of the window, that covers more than half of the window. Otherwise it returns null, meaning the document.
The tracker measures depth on that element. It listens to scroll in the capture phase on document, because an element's scroll does not bubble. It computes dy in the element's unrolled content: pageY plus its scrollTop for a target inside it, plus its hidden range for a point below it, over scrollHeight plus that range. A point beside or above the element gets no adjustment. The field format is unchanged.
The capture script receives the same function through the snapshot context. It marks the element data-marketing-scroll-root in the serialized DOM and records the unrolled height as document.height. On load, useSnapshotFrame unrolls a marked capture before measuring (utils/snapshotScrollRoot.ts):
- the root and its ancestors get
height: auto,max-height: noneandoverflow-y: visible, and a horizontal clip becomesclip - a fixed or absolute box becomes absolute with
bottom: auto - an item of a column flexbox keeps its content height
The frame's document then grows to the full content. A capture without the mark renders as before.