Skip to content

Commit fe5c2be

Browse files
sammacbethclaudemuodov
authored
Collect popup coordinates during crawl (#214)
* Hit-test for popups with a dense grid and store where popups are Turn on autoconsent's enableHeuristicHitTest, and hit-test a dense grid in the scrape script: 11 columns, and rows every 30px from the top and bottom edges. The grid includes every point of autoconsent's default grid, so the default grid can be replayed from the data. Each scraped popup now carries the search that found it, its position on the page, its CSS position and the grid points that reached it. Each frame carries its viewport size and scroll offset. SCRAPE_VERSION is now 3. The ClickHouse popup and frame tables get matching columns. Existing tables need these columns added before the next import, since rows are inserted by position. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Send popup hit points to ClickHouse as named tuple objects ClickHouse JSON input reads a named tuple from an object, so the [x, y] arrays of the scrape output failed to parse on import. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Use autoconsent's default hit-test grid in the scrape script The dense grid was for test crawls, to find out where popups are hit. Hit points now come from autoconsent's default grid. SCRAPE_VERSION is now 4. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Require autoconsent 17 for its popup hit-testing The popup positions and hit-test grid rely on autoconsent's elementAtPoint popup detection (enableHeuristicHitTest, popup source and hitPoints), which was added in autoconsent 17.0.0. ^16.51.0 never resolves to 17.x, so the scrapeScript tests ran against 16.x without it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Maxim Tsoy <mtsoy@duckduckgo.com>
1 parent d816db6 commit fe5c2be

8 files changed

Lines changed: 220 additions & 37 deletions

File tree

‎collectors/CookiePopups/scrapeScript.js‎

Lines changed: 61 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/* global window, document, HTMLElement, Node, NodeFilter, location, NamedNodeMap, DOMTokenList, DOMException, CSS */
1+
/* global window, document, HTMLElement, ShadowRoot, Node, NodeFilter, location, NamedNodeMap, DOMTokenList, DOMException, CSS */
22

33
// Popup and button discovery comes from autoconsent (window.autoconsentHeuristics), which CookiePopupsCollector
44
// injects into the same isolated world before this script runs.
@@ -7,12 +7,13 @@ const LIMIT_TEXT_LENGTH = 150000;
77
// autoconsent stops walking the DOM after this many ms; it uses 100ms in browsers, the crawler can afford more
88
const POPUP_SEARCH_TIMEOUT = 2000;
99
// bump when the shape or semantics of the scraped data change
10-
const SCRAPE_VERSION = 2;
10+
// 4: hit points come from autoconsent's default hit-test grid; version 3 used a dense grid (11 columns, rows every 30px)
11+
const SCRAPE_VERSION = 4;
1112

1213
/**
1314
* @typedef {import('../../node_modules/@duckduckgo/autoconsent/lib/types').ButtonData} HeuristicButton
1415
* @typedef {{
15-
* getPotentialPopups(timeout?: number): import('../../node_modules/@duckduckgo/autoconsent/lib/types').PopupData[],
16+
* getPotentialPopups(timeout?: number, hitTest?: boolean): import('../../node_modules/@duckduckgo/autoconsent/lib/types').PopupData[],
1617
* getButtonData(el: HTMLElement): HeuristicButton[],
1718
* }} AutoconsentHeuristics
1819
*/
@@ -267,6 +268,55 @@ function serializeButton(button) {
267268
};
268269
}
269270

271+
/**
272+
* @param {HTMLElement} el
273+
* @returns {string}
274+
*/
275+
function getCssPosition(el) {
276+
/** @type {Node | null} */
277+
let node = el;
278+
while (node) {
279+
if (node instanceof HTMLElement) {
280+
const position = window.getComputedStyle(node).position;
281+
if (position === 'fixed' || position === 'sticky') {
282+
return position;
283+
}
284+
}
285+
node = node.parentNode instanceof ShadowRoot ? node.parentNode.host : node.parentNode;
286+
}
287+
return window.getComputedStyle(el).position;
288+
}
289+
290+
/**
291+
* @param {HTMLElement} el
292+
* @returns {import('../CookiePopupsCollector').PopupRect}
293+
*/
294+
function getPageRect(el) {
295+
const rect = el.getBoundingClientRect();
296+
return {
297+
x: Math.round(rect.left + window.scrollX),
298+
y: Math.round(rect.top + window.scrollY),
299+
width: Math.round(rect.width),
300+
height: Math.round(rect.height),
301+
};
302+
}
303+
304+
/**
305+
* @param {import('../../node_modules/@duckduckgo/autoconsent/lib/types').PopupData} popup
306+
* @returns {import('../CookiePopupsCollector').PopupData}
307+
*/
308+
function serializePopup(popup) {
309+
return {
310+
text: popup.text,
311+
selector: getUniqueSelector(popup.element),
312+
buttons: popup.buttons.map(serializeButton),
313+
source: popup.source,
314+
rect: getPageRect(popup.element),
315+
cssPosition: getCssPosition(popup.element),
316+
hitPoints: popup.hitPoints ?? [],
317+
};
318+
}
319+
270320
/**
271321
* @returns {import('../CookiePopupsCollector').ScrapeScriptResult}
272322
*/
@@ -284,18 +334,21 @@ function scrapePage() {
284334
return { ...base, buttons: [], cleanedText: '', potentialPopups: [] };
285335
}
286336

337+
const viewport = {
338+
width: window.innerWidth,
339+
height: window.innerHeight,
340+
scrollX: Math.round(window.scrollX),
341+
scrollY: Math.round(window.scrollY),
342+
};
287343
return {
288344
...base,
345+
viewport,
289346
buttons: heuristics
290347
.getButtonData(document.documentElement)
291348
.filter((b) => isInViewport(b.element))
292349
.map(serializeButton),
293350
cleanedText: getDocumentText().slice(0, LIMIT_TEXT_LENGTH),
294-
potentialPopups: heuristics.getPotentialPopups(POPUP_SEARCH_TIMEOUT).map((popup) => ({
295-
text: popup.text,
296-
selector: getUniqueSelector(popup.element),
297-
buttons: popup.buttons.map(serializeButton),
298-
})),
351+
potentialPopups: heuristics.getPotentialPopups(POPUP_SEARCH_TIMEOUT, true).map(serializePopup),
299352
};
300353
}
301354

‎collectors/CookiePopupsCollector.js‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ class CookiePopupsCollector extends ContentScriptCollector {
199199
enablePrehide: false,
200200
enableCosmeticRules: true,
201201
enableHeuristicDetection: true,
202+
enableHeuristicHitTest: true,
202203
heuristicMode: 'tier2',
203204
detectRetries: 20,
204205
isMainWorld: false,
@@ -625,6 +626,7 @@ class CookiePopupsCollector extends ContentScriptCollector {
625626
* @typedef ScrapeScriptResult
626627
* @property {boolean} isTop
627628
* @property {string} origin
629+
* @property {Viewport} [viewport] absent in older crawls, and in frames that are not inspected
628630
* @property {string} cleanedText
629631
* @property {ButtonData[]} buttons
630632
* @property {PopupData[]} potentialPopups
@@ -635,11 +637,31 @@ class CookiePopupsCollector extends ContentScriptCollector {
635637
* @property {ButtonData[]} [otherButtons]
636638
*/
637639

640+
/**
641+
* @typedef Viewport
642+
* @property {number} width
643+
* @property {number} height
644+
* @property {number} scrollX
645+
* @property {number} scrollY
646+
*/
647+
648+
/**
649+
* @typedef PopupRect position on the page (viewport position plus scroll), in CSS px; for popups in a frame, on the frame's page
650+
* @property {number} x
651+
* @property {number} y
652+
* @property {number} width
653+
* @property {number} height
654+
*/
655+
638656
/**
639657
* @typedef PopupData
640658
* @property {string} text
641659
* @property {string} selector
642660
* @property {ButtonData[]} buttons
661+
* @property {'walk'|'hitTest'|'frame'} [source] which autoconsent search found the popup
662+
* @property {PopupRect} [rect]
663+
* @property {string} [cssPosition] 'fixed' or 'sticky' when the popup or an ancestor is, otherwise the popup's own position
664+
* @property {[number, number][]} [hitPoints] viewport points ([x, y] in CSS px) whose hit test reached the popup
643665
* @property {boolean} [llmMatch]
644666
* @property {boolean} [regexMatch]
645667
* @property {ButtonData[]} [rejectButtons]

‎package-lock.json‎

Lines changed: 5 additions & 17 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
},
4545
"dependencies": {
4646
"@clickhouse/client": "^1.11.1",
47-
"@duckduckgo/autoconsent": "^16.51.0",
47+
"@duckduckgo/autoconsent": "^17.1.0",
4848
"@types/commander": "^2.12.0",
4949
"async": "^3.2.6",
5050
"chalk": "^4.1.2",

‎reporters/ClickhouseReporter.js‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,11 @@ const TABLE_DEFINITIONS = [
120120
llmPopupDetected Nullable(Bool),
121121
regexPopupDetected Nullable(Bool),
122122
buttonCount UInt32,
123-
potentialPopupCount UInt16
123+
potentialPopupCount UInt16,
124+
viewportWidth Nullable(UInt16),
125+
viewportHeight Nullable(UInt16),
126+
scrollX Nullable(Int32),
127+
scrollY Nullable(Int32)
124128
) ENGINE = ReplicatedMergeTree
125129
PRIMARY KEY(crawlId, pageId, frameId)`,
126130
`CREATE TABLE IF NOT EXISTS cookiePopupPopups ON CLUSTER 'ch-prod-cluster' (
@@ -132,7 +136,14 @@ const TABLE_DEFINITIONS = [
132136
text String CODEC(ZSTD(3)),
133137
llmMatch Nullable(Bool),
134138
regexMatch Nullable(Bool),
135-
buttonCount UInt16
139+
buttonCount UInt16,
140+
source LowCardinality(Nullable(String)),
141+
x Nullable(Int32),
142+
y Nullable(Int32),
143+
width Nullable(UInt32),
144+
height Nullable(UInt32),
145+
cssPosition LowCardinality(Nullable(String)),
146+
hitPoints Array(Tuple(x UInt16, y UInt16))
136147
) ENGINE = ReplicatedMergeTree
137148
PRIMARY KEY(crawlId, pageId, frameId, popupId)`,
138149
`CREATE TABLE IF NOT EXISTS cookiePopupButtons ON CLUSTER 'ch-prod-cluster' (
@@ -253,6 +264,10 @@ function scrapedFramesToRows(crawlId, pageId, scrapedFrames) {
253264
frame.regexPopupDetected ?? null,
254265
frame.buttons.length,
255266
frame.potentialPopups.length,
267+
frame.viewport?.width ?? null,
268+
frame.viewport?.height ?? null,
269+
frame.viewport?.scrollX ?? null,
270+
frame.viewport?.scrollY ?? null,
256271
]);
257272
frame.potentialPopups.forEach((popup, popupId) => {
258273
popups.push([
@@ -265,6 +280,14 @@ function scrapedFramesToRows(crawlId, pageId, scrapedFrames) {
265280
popup.llmMatch ?? null,
266281
popup.regexMatch ?? null,
267282
popup.buttons.length,
283+
popup.source ?? null,
284+
popup.rect?.x ?? null,
285+
popup.rect?.y ?? null,
286+
popup.rect?.width ?? null,
287+
popup.rect?.height ?? null,
288+
popup.cssPosition ?? null,
289+
// JSON input reads named tuples from objects, not arrays
290+
(popup.hitPoints ?? []).map(([x, y]) => ({ x, y })),
268291
]);
269292
mergeButtonLabels(popup).forEach(({ button, isReject }, buttonId) => {
270293
buttons.push([

‎tests/collectors/CookiePopupsCollector.mocha.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ describe('CookiePopupsCollector', () => {
9696
enablePrehide: false,
9797
enableCosmeticRules: true,
9898
enableHeuristicDetection: true,
99+
enableHeuristicHitTest: true,
99100
heuristicMode: 'tier2',
100101
detectRetries: 20,
101102
isMainWorld: false,
@@ -133,6 +134,7 @@ describe('CookiePopupsCollector', () => {
133134
enablePrehide: false,
134135
enableCosmeticRules: true,
135136
enableHeuristicDetection: true,
137+
enableHeuristicHitTest: true,
136138
heuristicMode: 'tier2',
137139
detectRetries: 20,
138140
isMainWorld: false,

‎tests/collectors/scrapeScript.mocha.js‎

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,27 @@ const PAGE = `
1717
<footer><a href="#" id="dns">Do not sell my personal information</a></footer>
1818
</body></html>`;
1919

20+
// a banner in the normal page flow, which only hit-testing finds
21+
const IN_FLOW_PAGE = `
22+
<html><body style="margin: 0">
23+
<div id="inflow" style="height: 100px;">
24+
<p style="margin: 0">We use cookies to improve your experience. Read our <a href="#">Privacy Policy</a>.</p>
25+
<button>Reject all</button>
26+
<button>Accept all</button>
27+
</div>
28+
<div style="height: 3000px"></div>
29+
</body></html>`;
30+
2031
/**
2132
* @param {import('puppeteer').Page} page
2233
* @param {boolean} [withAutoconsent] inject autoconsent first, as CookiePopupsCollector does
34+
* @param {string} [html]
35+
* @param {number} [scrollY] scroll the page before scraping
2336
* @returns {Promise<import('../../collectors/CookiePopupsCollector').ScrapeScriptResult>}
2437
*/
25-
async function scrape(page, withAutoconsent = true) {
26-
await page.setContent(PAGE);
38+
async function scrape(page, withAutoconsent = true, html = PAGE, scrollY = 0) {
39+
await page.setContent(html);
40+
await page.evaluate((y) => window.scrollTo(0, y), scrollY);
2741
if (withAutoconsent) {
2842
await page.evaluate(`window.testBinding = () => {};\n${getAutoconsentContentScript('testBinding')}`);
2943
}
@@ -61,7 +75,7 @@ describe('scrapeScript', function () {
6175
it('uses autoconsent popup and button discovery', async () => {
6276
const result = await scrape(page);
6377
assert.strictEqual(result.isTop, true);
64-
assert.strictEqual(result.scrapeVersion, 2);
78+
assert.strictEqual(result.scrapeVersion, 4);
6579
assert.ok(result.cleanedText.includes('We use cookies'));
6680

6781
const banner = result.potentialPopups.find((p) => p.selector.includes('#banner'));
@@ -80,6 +94,44 @@ describe('scrapeScript', function () {
8094
);
8195
});
8296

97+
it('records the viewport and where the popups are', async () => {
98+
const result = await scrape(page);
99+
const { width, height } = page.viewport() ?? { width: 0, height: 0 };
100+
assert.deepStrictEqual(result.viewport, { width, height, scrollX: 0, scrollY: 0 });
101+
102+
const banner = result.potentialPopups.find((p) => p.selector.includes('#banner'));
103+
assert.ok(banner?.rect);
104+
assert.strictEqual(banner.source, 'walk');
105+
assert.strictEqual(banner.cssPosition, 'fixed');
106+
assert.deepStrictEqual([banner.rect.x, banner.rect.width], [0, width]);
107+
assert.strictEqual(banner.rect.y + banner.rect.height, height);
108+
// autoconsent's default grid hits the fixed banner along the bottom edge, in each of its 3 columns
109+
assert.ok(banner.hitPoints && banner.hitPoints.length >= 3);
110+
assert.ok(banner.hitPoints.every(([, y]) => y >= banner.rect.y && y < height));
111+
});
112+
113+
it('records positions on the page, not in the viewport', async () => {
114+
const result = await scrape(page, true, PAGE, 500);
115+
assert.strictEqual(result.viewport?.scrollY, 500);
116+
const banner = result.potentialPopups.find((p) => p.selector.includes('#banner'));
117+
assert.strictEqual(banner?.rect?.y, 500 + result.viewport.height - banner.rect.height);
118+
});
119+
120+
it('hit-tests for banners in the normal page flow', async () => {
121+
const result = await scrape(page, true, IN_FLOW_PAGE);
122+
const banner = result.potentialPopups.find((p) => p.selector.includes('#inflow'));
123+
assert.ok(banner, 'in-flow banner is found by hit-testing');
124+
assert.strictEqual(banner.source, 'hitTest');
125+
assert.strictEqual(banner.cssPosition, 'static');
126+
assert.deepStrictEqual(banner.rect, { x: 0, y: 0, width: result.viewport?.width, height: 100 });
127+
// autoconsent's default grid: columns at 10%, 50% and 90%, rows 30 and 90px from the top
128+
const xs = [0.1, 0.5, 0.9].map((c) => Math.round(c * (result.viewport?.width ?? 0)));
129+
assert.deepStrictEqual(
130+
banner.hitPoints,
131+
[30, 90].flatMap((y) => xs.map((x) => [x, y])),
132+
);
133+
});
134+
83135
it('limits page-level buttons to the viewport', async () => {
84136
const result = await scrape(page);
85137
const texts = result.buttons.map((b) => b.text);

0 commit comments

Comments
 (0)