diff --git a/src/client/AdForensics.ts b/src/client/AdForensics.ts new file mode 100644 index 00000000000..d02b2a28bfe --- /dev/null +++ b/src/client/AdForensics.ts @@ -0,0 +1,277 @@ +import type { SlotRenderEndedEvent } from "./GoogleTag"; + +const GAM_IFRAME_PREFIX = "google_ads_iframe_"; +const MAX_RENDERS = 30; +// Every unit we load: gutter rails, header, bottom rail, the three in-game +// units and the corner video. +const UNITS_IN_REPORT = 8; +// Measured on screen, so it must catch a 320x50 unit half off the edge +// (8,000) while skipping the 1px strips bidder and ID-sync scripts leave +// across the viewport (3,840 on a 4K screen). +const MIN_FRAME_AREA = 7_000; + +interface RenderedCreative { + slotElementId: string; + // GPT's per-render id on the creative's iframe. Iframe ids are not unique + // to a render: a later load of the same unit can reuse them. + containerId: string; + adUnitPath: string; + size: string; + creativeId: string; + lineItemId: string; + advertiserId: string; + campaignId: string; + bidder: string; + bidId: string; + advertiserDomain: string; +} + +// Every render, for matching a frame from an earlier load still on screen. +const renders: RenderedCreative[] = []; +// The newest render of each unit, in order of render. Kept apart from the +// bounded history, which the in-game units' refreshes cycle through within +// minutes. +const newestByUnit = new Map(); +let tracking = false; + +/** + * Records every creative GPT renders. A destroyed slot takes its creative + * details with it, so they have to be kept from render time to be reported + * once the ad turns up where it should not be. + */ +export function trackAdCreatives(): void { + if (tracking) return; + tracking = true; + try { + window.googletag ??= { cmd: [] }; + window.googletag.cmd.push(() => { + window.googletag + ?.pubads?.() + .addEventListener("slotRenderEnded", recordRender); + }); + } catch (e) { + console.warn("Failed to track ad creatives:", e); + } +} + +function recordRender(event: SlotRenderEndedEvent): void { + if (event.isEmpty) return; + try { + const { slot } = event; + const targeting = (key: string) => slot.getTargeting(key)[0] ?? ""; + const render: RenderedCreative = { + slotElementId: slot.getSlotElementId(), + containerId: + document + .getElementById(slot.getSlotElementId()) + ?.querySelector(`iframe[id^="${GAM_IFRAME_PREFIX}"]`) + ?.getAttribute("data-google-container-id") ?? "", + adUnitPath: slot.getAdUnitPath(), + size: Array.isArray(event.size) + ? event.size.join("x") + : (event.size ?? ""), + // The source-agnostic ids also cover backfill, where GAM's are null. + creativeId: idString(event.sourceAgnosticCreativeId ?? event.creativeId), + lineItemId: idString(event.sourceAgnosticLineItemId ?? event.lineItemId), + advertiserId: idString(event.advertiserId), + campaignId: idString(event.campaignId), + // Every header-bidding win renders through the same Prebid line item, + // so only the bid itself can name the creative. + bidder: targeting("hb_bidder"), + bidId: targeting("hb_adid"), + advertiserDomain: targeting("hb_adomain"), + }; + renders.push(render); + if (renders.length > MAX_RENDERS) renders.shift(); + newestByUnit.delete(render.adUnitPath); + newestByUnit.set(render.adUnitPath, render); + } catch (e) { + console.warn("Failed to record an ad render:", e); + } +} + +function idString(id: number | null | undefined): string { + return id === null || id === undefined ? "" : String(id); +} + +function renderedIn( + el: Element, +): { render: RenderedCreative; match: "frame" | "path" | "slot" } | null { + const frames = [ + ...(el.matches("iframe") ? [el] : []), + ...el.querySelectorAll(`iframe[id^="${GAM_IFRAME_PREFIX}"]`), + ]; + const containerIds = new Set( + frames.map((frame) => frame.getAttribute("data-google-container-id")), + ); + for (let i = renders.length - 1; i >= 0; i--) { + if ( + renders[i].containerId !== "" && + containerIds.has(renders[i].containerId) + ) { + return { render: renders[i], match: "frame" }; + } + } + const newest = newestRenders(); + // The newest render of the unit, which may not be the one in this frame. + for (const render of newest) { + const framePrefix = `${GAM_IFRAME_PREFIX}${render.adUnitPath}_`; + // The rest must be the frame counter alone, so /foo cannot claim /foo_bar. + const isUnitFrame = (frame: Element) => + frame.id.startsWith(framePrefix) && + /^\d+$/.test(frame.id.slice(framePrefix.length)); + if (frames.some(isUnitFrame)) return { render, match: "path" }; + } + // Playwire reuses a unit's element (#pw-oop-bottom_rail) for every load, + // so the newest render into it may be an earlier load's. + for (const render of newest) { + const slotElement = document.getElementById(render.slotElementId); + if (slotElement !== null && el.contains(slotElement)) { + return { render, match: "slot" }; + } + } + return null; +} + +function newestRenders(): RenderedCreative[] { + return [...newestByUnit.values()].reverse(); +} + +/** + * Faro attributes for the creative that rendered inside `el`. Failing that, + * the newest creative of an ad unit whose path contains `adUnit`. Only a + * "frame" match is certain to be the creative on screen; `creativeMatch` + * says how it was found. + */ +export function creativeAttributes( + el: Element, + adUnit?: string, +): Record { + const found = renderedIn(el); + let match: string = found?.match ?? "none"; + let render = found?.render ?? null; + if (render === null && adUnit !== undefined) { + match = "unit"; + render = newestRenders().find((r) => r.adUnitPath.includes(adUnit)) ?? null; + } + return { + creativeMatch: render === null ? "none" : match, + creativeId: render?.creativeId ?? "", + lineItemId: render?.lineItemId ?? "", + advertiserId: render?.advertiserId ?? "", + campaignId: render?.campaignId ?? "", + bidder: render?.bidder ?? "", + bidId: render?.bidId ?? "", + advertiserDomain: render?.advertiserDomain ?? "", + }; +} + +// The newest render of each unit, not the newest renders overall: the +// in-game units render as the bottom rail goes, and would push it out. +function recentCreatives(): string { + return newestRenders() + .slice(0, UNITS_IN_REPORT) + .map((r) => + [ + r.adUnitPath, + r.size, + r.creativeId, + r.lineItemId, + r.advertiserId, + r.bidder, + r.bidId, + r.advertiserDomain, + ].join("|"), + ) + .join(";"); +} + +export interface StrayAdFrame { + root: HTMLElement; + attributes: Record; +} + +/** + * Visible, ad-sized iframes outside our own UI (Lit custom elements) and + * outside Playwire's containers (a pw- id or class; the bottom rail has its + * own guard). + * A creative that breaks out of its slot and draws on the page itself shows + * up here, which the slot-based checks cannot see. + */ +export function findStrayAdFrames(): StrayAdFrame[] { + const found = new Map(); + for (const frame of document.querySelectorAll("iframe")) { + const root = unownedRoot(frame); + if (root === null || found.has(root)) continue; + const rect = frame.getBoundingClientRect(); + if (visibleArea(rect) < MIN_FRAME_AREA) continue; + if ( + frame.checkVisibility?.({ + opacityProperty: true, + visibilityProperty: true, + }) === false + ) { + continue; + } + const style = getComputedStyle(root); + found.set(root, { + root, + attributes: { + element: root.localName, + elementId: root.id, + elementClass: root.className.slice(0, 200), + position: style.position, + zIndex: style.zIndex, + frameId: frame.id.slice(0, 200), + frameOrigin: frameOrigin(frame), + frameRect: [rect.left, rect.top, rect.width, rect.height] + .map(Math.round) + .join(","), + ...creativeAttributes(root), + recentCreatives: recentCreatives(), + }, + }); + } + return [...found.values()]; +} + +// The body-level element holding `frame`, or null when that subtree is ours +// or Playwire's. +function unownedRoot(frame: HTMLIFrameElement): HTMLElement | null { + let el: HTMLElement = frame; + for (;;) { + if (customElements.get(el.localName) !== undefined) return null; + if (el.id.startsWith("pw-")) return null; + // The corner video's container has a class and no id. + for (const name of el.classList) if (name.startsWith("pw-")) return null; + const parent = el.parentElement; + if (parent === null) return null; + if (parent === document.body || parent === document.documentElement) { + return el; + } + el = parent; + } +} + +function visibleArea(rect: DOMRect): number { + const width = + Math.min(rect.right, window.innerWidth) - Math.max(rect.left, 0); + const height = + Math.min(rect.bottom, window.innerHeight) - Math.max(rect.top, 0); + return Math.max(0, width) * Math.max(0, height); +} + +function frameOrigin(frame: HTMLIFrameElement): string { + if (frame.src === "") return ""; + try { + return new URL(frame.src, location.href).origin; + } catch { + return ""; + } +} + +export function resetAdForensics(): void { + renders.length = 0; + newestByUnit.clear(); + tracking = false; +} diff --git a/src/client/Admiral.ts b/src/client/Admiral.ts index 0dc74c849ba..e3ffa2e8f48 100644 --- a/src/client/Admiral.ts +++ b/src/client/Admiral.ts @@ -23,15 +23,9 @@ type AdmiralFn = { s?: string; }; -interface GoogleTag { - cmd: Array<() => void>; - pubads?: () => { setTargeting: (key: string, value: string) => void }; -} - declare global { interface Window { admiral?: AdmiralFn; - googletag?: GoogleTag; } } diff --git a/src/client/GoogleTag.ts b/src/client/GoogleTag.ts new file mode 100644 index 00000000000..86296350b1b --- /dev/null +++ b/src/client/GoogleTag.ts @@ -0,0 +1,38 @@ +// The parts of Google Publisher Tag that Playwire's ramp.js loads and we read. + +export interface GptSlot { + getSlotElementId(): string; + getAdUnitPath(): string; + getTargeting(key: string): string[]; +} + +export interface SlotRenderEndedEvent { + slot: GptSlot; + isEmpty: boolean; + size: number[] | string | null; + advertiserId?: number | null; + campaignId?: number | null; + creativeId: number | null; + lineItemId: number | null; + sourceAgnosticCreativeId?: number | null; + sourceAgnosticLineItemId?: number | null; +} + +export interface PubAdsService { + setTargeting(key: string, value: string): void; + addEventListener( + type: "slotRenderEnded", + listener: (event: SlotRenderEndedEvent) => void, + ): void; +} + +export interface GoogleTag { + cmd: Array<() => void>; + pubads?: () => PubAdsService; +} + +declare global { + interface Window { + googletag?: GoogleTag; + } +} diff --git a/src/client/HomepagePromos.ts b/src/client/HomepagePromos.ts index 922c79218c2..41f227bf428 100644 --- a/src/client/HomepagePromos.ts +++ b/src/client/HomepagePromos.ts @@ -1,5 +1,10 @@ import { LitElement } from "lit"; import { customElement } from "lit/decorators.js"; +import { + creativeAttributes, + findStrayAdFrames, + trackAdCreatives, +} from "./AdForensics"; import { adGatekeeper } from "./AdGatekeeper"; import { menuChromeIsTornDown } from "./MenuChrome"; import { reportEvent } from "./Telemetry"; @@ -7,6 +12,7 @@ import { reportEvent } from "./Telemetry"; const BOTTOM_RAIL_ID = "pw-oop-bottom_rail"; const GAM_IFRAME_PREFIX = "google_ads_iframe_"; const STILL_VISIBLE_CHECK_MS = 2000; +const STRAY_FRAME_SCAN_MS = 1000; type DestroyUnitsResult = "resolved" | "rejected" | "unavailable"; @@ -54,6 +60,8 @@ export class HomepagePromos extends LitElement { private bottomRailDestroyedAt: number | null = null; private railDestroy: Promise | null = null; private railDestroyCount = 0; + private strayFrameScan: ReturnType | null = null; + private reportedStrayFrames = new WeakSet(); // The header ad ("flex" leaderboard, GumGum via Playwire) renders in a // #pw-oop-flex element that ramp.js nests inside a #pw-oop-flex_container @@ -75,6 +83,7 @@ export class HomepagePromos extends LitElement { connectedCallback() { super.connectedCallback(); + trackAdCreatives(); document.addEventListener("userMeResponse", this.onUserMeResponse); document.addEventListener("join-lobby", this.onJoinLobby); document.addEventListener("leave-lobby", this.onLeaveLobby); @@ -100,6 +109,7 @@ export class HomepagePromos extends LitElement { document.removeEventListener("join-lobby", this.onJoinLobby); document.removeEventListener("leave-lobby", this.onLeaveLobby); this.topAdMutation?.disconnect(); + this.stopStrayFrameScan(); this.topAdStyle?.disconnect(); this.topAdResize?.disconnect(); document.documentElement.style.removeProperty("--top-ad-height"); @@ -269,6 +279,7 @@ export class HomepagePromos extends LitElement { if (!this.bottomRailActive) return; this.bottomRailActive = false; this.bottomRailDestroyedAt = performance.now(); + this.startStrayFrameScan(); this.railDestroyCount++; this.railDestroy = this.destroyBottomRailUnit().then(() => { this.railDestroy = null; @@ -311,6 +322,8 @@ export class HomepagePromos extends LitElement { rail .querySelector(`iframe[id^="${GAM_IFRAME_PREFIX}"]`) ?.id.slice(GAM_IFRAME_PREFIX.length) ?? "", + // Read before the destroy, which takes the slot and its creative away. + ...creativeAttributes(rail, "bottom_rail"), }; console.log( `Bottom rail ad still on the page ${seconds}s after it was destroyed; destroying it again`, @@ -349,12 +362,49 @@ export class HomepagePromos extends LitElement { reportEvent("bottom_rail_in_game", { ...details, adSlot: creative.id.slice(GAM_IFRAME_PREFIX.length), + ...creativeAttributes(creative, "bottom_rail"), outcome: "still_visible", }); }, STILL_VISIBLE_CHECK_MS); }); } + // Polled rather than driven by the body observer: a frame can appear + // through a style change alone, and watching every attribute in a game + // costs more than a scan. + private startStrayFrameScan(): void { + this.strayFrameScan ??= setInterval( + () => this.reportStrayAdFrames(), + STRAY_FRAME_SCAN_MS, + ); + } + + private stopStrayFrameScan(): void { + if (this.strayFrameScan !== null) clearInterval(this.strayFrameScan); + this.strayFrameScan = null; + } + + // Reported, not removed: the match is a heuristic, and taking down + // something that is not an ad would break the page for the player. + private reportStrayAdFrames(): void { + if (this.bottomRailDestroyedAt === null || !menuChromeIsTornDown()) { + this.stopStrayFrameScan(); + return; + } + for (const { root, attributes } of findStrayAdFrames()) { + if (this.reportedStrayFrames.has(root)) continue; + this.reportedStrayFrames.add(root); + reportEvent("ad_frame_in_game", { + gameID: this.lobby?.gameID ?? "", + lobbySource: this.lobby?.source ?? "", + secondsAfterDestroy: String( + Math.round((performance.now() - this.bottomRailDestroyedAt) / 1000), + ), + ...attributes, + }); + } + } + private loadGutterAds(): void { if (!window.adsEnabled) return; console.log("loading ramp gutter rails and header ad"); diff --git a/src/client/Telemetry.ts b/src/client/Telemetry.ts index c7aea20f9a4..b9d1d1b9b87 100644 --- a/src/client/Telemetry.ts +++ b/src/client/Telemetry.ts @@ -164,11 +164,11 @@ const DROPPED_EVENTS = new Set(["securitypolicyviolation"]); // Sent from every session, whatever its sampling: each one is looked up by // game ID from a player's report, and ad removals are reported to the ad // partner. Only for events rare enough not to move the per-session bill. -const UNSAMPLED_EVENTS = new Set(["bottom_rail_in_game"]); -// Unsampled events skip isRepeated, so they get a page-wide cap of their own +const UNSAMPLED_EVENTS = new Set(["bottom_rail_in_game", "ad_frame_in_game"]); +// Unsampled events skip isRepeated, so each gets a page-wide cap of its own // against an ad script stuck re-adding what we remove. const MAX_UNSAMPLED_EVENTS = 20; -let unsampledSent = 0; +const unsampledSent = new Map(); /** * Forwards console[method] calls made from our bundle to Faro as log lines @@ -220,8 +220,9 @@ function filterSignal( const name = (item.payload as { name?: unknown } | null)?.name; if (typeof name === "string" && DROPPED_EVENTS.has(name)) return null; if (typeof name === "string" && UNSAMPLED_EVENTS.has(name)) { - if (unsampledSent >= MAX_UNSAMPLED_EVENTS) return null; - unsampledSent++; + const count = unsampledSent.get(name) ?? 0; + if (count >= MAX_UNSAMPLED_EVENTS) return null; + unsampledSent.set(name, count + 1); return slimBrowserMeta(scrubUrls(item)); } } @@ -334,7 +335,7 @@ export function resetTelemetry(): void { faroPromise = null; sent.clear(); sentTotal = 0; - unsampledSent = 0; + unsampledSent.clear(); } /** diff --git a/tests/client/AdForensics.test.ts b/tests/client/AdForensics.test.ts new file mode 100644 index 00000000000..8a5d8cd1899 --- /dev/null +++ b/tests/client/AdForensics.test.ts @@ -0,0 +1,272 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + creativeAttributes, + findStrayAdFrames, + resetAdForensics, + trackAdCreatives, +} from "../../src/client/AdForensics"; +import type { SlotRenderEndedEvent } from "../../src/client/GoogleTag"; + +const railPath = "/154013155/1025558-w:75940-bottom_rail"; + +let onRender: (event: SlotRenderEndedEvent) => void; + +function render( + slotElementId: string, + adUnitPath: string, + extra: Partial = {}, + targeting: Record = {}, +): void { + onRender({ + slot: { + getSlotElementId: () => slotElementId, + getAdUnitPath: () => adUnitPath, + getTargeting: (key) => (key in targeting ? [targeting[key]] : []), + }, + isEmpty: false, + size: [728, 90], + creativeId: 111, + lineItemId: 222, + advertiserId: 333, + campaignId: 444, + ...extra, + }); +} + +function placeFrame( + parent: Element, + id: string, + width = 728, + height = 90, + containerId = "", +) { + const frame = document.createElement("iframe"); + frame.id = id; + if (containerId !== "") { + frame.setAttribute("data-google-container-id", containerId); + } + frame.getBoundingClientRect = () => + new DOMRect(100, window.innerHeight - height, width, height); + parent.appendChild(frame); + return frame; +} + +beforeEach(() => { + resetAdForensics(); + const cmd: Array<() => void> = []; + window.googletag = { + cmd, + pubads: () => ({ + setTargeting: () => {}, + addEventListener: (_type, listener) => (onRender = listener), + }), + }; + trackAdCreatives(); + cmd.splice(0).forEach((fn) => fn()); +}); + +afterEach(() => { + document.body.replaceChildren(); + delete window.googletag; +}); + +describe("creativeAttributes", () => { + it("names the creative whose GAM iframe is inside the element", () => { + const rail = document.body.appendChild(document.createElement("div")); + rail.id = "rail-slot"; + placeFrame(rail, `google_ads_iframe_${railPath}_0`, 728, 90, "7"); + render( + "rail-slot", + railPath, + {}, + { + hb_bidder: "rubicon", + hb_adid: "3f2a", + hb_adomain: "example.com", + }, + ); + render("other-slot", "/154013155/1025558-w:75940-left_rail", { + creativeId: 999, + }); + + expect(creativeAttributes(rail)).toEqual({ + creativeMatch: "frame", + creativeId: "111", + lineItemId: "222", + advertiserId: "333", + campaignId: "444", + bidder: "rubicon", + bidId: "3f2a", + advertiserDomain: "example.com", + }); + }); + + it("is unsure of a frame a later load of the unit could have reused", () => { + const slot = document.body.appendChild(document.createElement("div")); + slot.id = "rail-slot"; + const frame = placeFrame( + slot, + `google_ads_iframe_${railPath}_0`, + 728, + 90, + "1", + ); + render("rail-slot", railPath, { creativeId: 1 }); + frame.setAttribute("data-google-container-id", "2"); + render("rail-slot", railPath, { creativeId: 2 }); + slot.remove(); + const stale = document.body.appendChild(document.createElement("div")); + placeFrame(stale, `google_ads_iframe_${railPath}_0`, 728, 90, "1"); + + expect(creativeAttributes(stale)).toMatchObject({ + creativeMatch: "frame", + creativeId: "1", + }); + stale.firstElementChild?.removeAttribute("data-google-container-id"); + expect(creativeAttributes(stale)).toMatchObject({ + creativeMatch: "path", + creativeId: "2", + }); + }); + + it("does not take a longer unit's frame for a shorter unit's", () => { + render("rail-slot", railPath, { creativeId: 1 }); + const other = document.body.appendChild(document.createElement("div")); + placeFrame(other, `google_ads_iframe_${railPath}_bar_0`); + + expect(creativeAttributes(other).creativeMatch).toBe("none"); + }); + + it("prefers the source-agnostic ids, which backfill fills in", () => { + render("rail-slot", railPath, { + creativeId: null, + lineItemId: null, + sourceAgnosticCreativeId: 555, + sourceAgnosticLineItemId: 666, + }); + const slot = document.body.appendChild(document.createElement("div")); + slot.id = "rail-slot"; + + expect(creativeAttributes(slot)).toMatchObject({ + creativeMatch: "slot", + creativeId: "555", + lineItemId: "666", + }); + }); + + it("falls back to the newest render of the unit, and says so", () => { + render("rail-slot", railPath, { creativeId: 1 }); + render("rail-slot", railPath, { creativeId: 2 }); + const empty = document.body.appendChild(document.createElement("div")); + + expect(creativeAttributes(empty, "bottom_rail")).toMatchObject({ + creativeMatch: "unit", + creativeId: "2", + }); + expect(creativeAttributes(empty)).toMatchObject({ + creativeMatch: "none", + creativeId: "", + }); + }); + + it("ignores empty renders", () => { + render("rail-slot", railPath, { isEmpty: true }); + const empty = document.body.appendChild(document.createElement("div")); + + expect(creativeAttributes(empty, "bottom_rail").creativeMatch).toBe("none"); + }); +}); + +describe("findStrayAdFrames", () => { + it("reports an ad-sized iframe drawn straight onto the page", () => { + render("rail-slot", railPath); + const overlay = document.body.appendChild(document.createElement("div")); + overlay.id = "takeover"; + overlay.style.position = "fixed"; + const frame = placeFrame(overlay, "creative"); + frame.src = "https://ads.example.net/creative.html?id=1"; + + const stray = findStrayAdFrames(); + + expect(stray).toHaveLength(1); + expect(stray[0].root).toBe(overlay); + expect(stray[0].attributes).toMatchObject({ + element: "div", + elementId: "takeover", + position: "fixed", + frameId: "creative", + frameOrigin: "https://ads.example.net", + frameRect: `100,${window.innerHeight - 90},728,90`, + creativeMatch: "none", + recentCreatives: `${railPath}|728x90|111|222|333|||`, + }); + }); + + it("keeps the rail in the recent creatives after other units render", () => { + render("rail-slot", railPath, { creativeId: 1 }); + render("rail-slot", railPath, { creativeId: 2 }); + for (const unit of ["left1", "left3", "left4"]) { + render(unit, `/154013155/1025558-w:75940-${unit}`, { creativeId: 9 }); + } + const overlay = document.body.appendChild(document.createElement("div")); + placeFrame(overlay, "creative"); + + const recent = findStrayAdFrames()[0].attributes.recentCreatives.split(";"); + + expect(recent).toHaveLength(4); + expect(recent[3]).toBe(`${railPath}|728x90|2|222|333|||`); + }); + + it("still knows the rail's creative after a long game of refreshes", () => { + render("rail-slot", railPath, { creativeId: 2 }); + for (let i = 0; i < 40; i++) { + render("left1", "/154013155/1025558-w:75940-left1", { creativeId: i }); + } + const empty = document.body.appendChild(document.createElement("div")); + const overlay = document.body.appendChild(document.createElement("div")); + placeFrame(overlay, "creative"); + + expect(creativeAttributes(empty, "bottom_rail")).toMatchObject({ + creativeMatch: "unit", + creativeId: "2", + }); + expect(findStrayAdFrames()[0].attributes.recentCreatives).toContain( + `${railPath}|728x90|2|`, + ); + }); + + it("leaves our own UI and Playwire's containers alone", () => { + customElements.define("stray-test-hud", class extends HTMLElement {}); + const hud = document.body.appendChild( + document.createElement("stray-test-hud"), + ); + placeFrame(hud.appendChild(document.createElement("div")), "ours"); + const rail = document.body.appendChild(document.createElement("div")); + rail.id = "pw-oop-bottom_rail"; + placeFrame(rail, "rail"); + const corner = document.body.appendChild(document.createElement("div")); + corner.className = "pw-corner-ad-video"; + placeFrame(corner, "corner"); + + expect(findStrayAdFrames()).toEqual([]); + }); + + it("reports a small unit hanging half off the bottom of the screen", () => { + const overlay = document.body.appendChild(document.createElement("div")); + const frame = placeFrame(overlay, "half"); + frame.getBoundingClientRect = () => + new DOMRect(0, window.innerHeight - 25, 320, 50); + + expect(findStrayAdFrames()).toHaveLength(1); + }); + + it("skips frames too small or off screen to be an ad on display", () => { + const strip = placeFrame(document.body, "strip"); + strip.getBoundingClientRect = () => new DOMRect(0, 0, 3840, 1); + placeFrame(document.body, "pixel", 1, 1); + const offscreen = placeFrame(document.body, "parked"); + offscreen.getBoundingClientRect = () => new DOMRect(-1000, -1000, 728, 90); + + expect(findStrayAdFrames()).toEqual([]); + }); +}); diff --git a/tests/client/HomepagePromos.test.ts b/tests/client/HomepagePromos.test.ts index 9f084e08ba6..d26bc009015 100644 --- a/tests/client/HomepagePromos.test.ts +++ b/tests/client/HomepagePromos.test.ts @@ -1,11 +1,24 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import "../../src/client/HomepagePromos"; +import type { SlotRenderEndedEvent } from "../../src/client/GoogleTag"; import type { HomepagePromos } from "../../src/client/HomepagePromos"; import { hideMenuChrome, restoreMenuChrome } from "../../src/client/MenuChrome"; import { reportEvent } from "../../src/client/Telemetry"; vi.mock("../../src/client/Telemetry", () => ({ reportEvent: vi.fn() })); +// GPT, already loaded: subscribes to renders as it connects. +let onRender: (event: SlotRenderEndedEvent) => void = () => {}; +window.googletag = { + cmd: { + push: (fn: () => void) => fn(), + } as unknown as Array<() => void>, + pubads: () => ({ + setTargeting: () => {}, + addEventListener: (_type, listener) => (onRender = listener), + }), +}; + // The index.html stub before ramp.js loads: a queue and nothing else. drain() // stands in for ramp.js arriving and running whatever was queued. function stubRamp() { @@ -127,6 +140,7 @@ describe("HomepagePromos bottom rail after its destroy", () => { rail.className = "pw-tag pointer-modifier pw-size-728x90"; const creative = document.createElement("iframe"); creative.id = `google_ads_iframe_${slot}`; + creative.setAttribute("data-google-container-id", "4"); rail.appendChild(creative); document.body.appendChild(rail); return rail; @@ -158,6 +172,19 @@ describe("HomepagePromos bottom rail after its destroy", () => { await flush(); const rail = renderRail(); + onRender({ + slot: { + getSlotElementId: () => "pw-oop-bottom_rail", + getAdUnitPath: () => slot.slice(0, -"_0".length), + getTargeting: (key) => (key === "hb_bidder" ? ["rubicon"] : []), + }, + isEmpty: false, + size: [728, 90], + creativeId: 138512345678, + lineItemId: 6789012345, + advertiserId: 4567, + campaignId: 8901, + }); await flush(); expect(ramp.destroyUnits).toHaveBeenCalledTimes(2); @@ -168,6 +195,14 @@ describe("HomepagePromos bottom rail after its destroy", () => { secondsAfterDestroy: "0", size: "728x90", adSlot: slot, + creativeMatch: "frame", + creativeId: "138512345678", + lineItemId: "6789012345", + advertiserId: "4567", + campaignId: "8901", + bidder: "rubicon", + bidId: "", + advertiserDomain: "", destroyUnits: "resolved", removedBy: "openfront", outcome: "removed", @@ -334,3 +369,102 @@ describe("HomepagePromos bottom rail after its destroy", () => { expect(reportEvent).not.toHaveBeenCalled(); }); }); + +describe("HomepagePromos ad frames over the game", () => { + function joinLobby(): void { + document.dispatchEvent( + new CustomEvent("join-lobby", { + detail: { gameID: "cSkwPxCLWx", source: "public" }, + }), + ); + } + + function drawOverlay(): HTMLElement { + const overlay = document.createElement("div"); + overlay.id = "takeover"; + const frame = document.createElement("iframe"); + frame.getBoundingClientRect = () => new DOMRect(0, 600, 728, 90); + overlay.appendChild(frame); + return document.body.appendChild(overlay); + } + + beforeEach(() => { + vi.useFakeTimers(); + vi.mocked(reportEvent).mockClear(); + stubRamp(); + hideMenuChrome(); + joinLobby(); + }); + + afterEach(() => { + document.getElementById("takeover")?.remove(); + vi.useRealTimers(); + }); + + it("reports an ad frame drawn over the game once, and leaves it there", async () => { + promos.destroyBottomRail(); + await vi.advanceTimersByTimeAsync(0); + + const overlay = drawOverlay(); + await vi.advanceTimersByTimeAsync(1000); + document.body.appendChild(document.createElement("div")).remove(); + await vi.advanceTimersByTimeAsync(1000); + + expect(reportEvent).toHaveBeenCalledExactlyOnceWith( + "ad_frame_in_game", + expect.objectContaining({ + gameID: "cSkwPxCLWx", + lobbySource: "public", + elementId: "takeover", + frameRect: "0,600,728,90", + }), + ); + expect(overlay.isConnected).toBe(true); + }); + + it("reports an ad frame already over the game when the rail goes", async () => { + drawOverlay(); + promos.destroyBottomRail(); + await vi.advanceTimersByTimeAsync(1000); + + expect(reportEvent).toHaveBeenCalledWith( + "ad_frame_in_game", + expect.objectContaining({ elementId: "takeover" }), + ); + }); + + it("reports an ad frame that a style change alone brings on screen", async () => { + promos.destroyBottomRail(); + const overlay = drawOverlay(); + const frame = overlay.querySelector("iframe")!; + frame.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0); + await vi.advanceTimersByTimeAsync(1000); + expect(reportEvent).not.toHaveBeenCalled(); + + frame.getBoundingClientRect = () => new DOMRect(0, 600, 728, 90); + await vi.advanceTimersByTimeAsync(1000); + + expect(reportEvent).toHaveBeenCalledWith( + "ad_frame_in_game", + expect.objectContaining({ elementId: "takeover" }), + ); + }); + + it("ignores ad frames during spawn, where the bottom rail belongs", async () => { + drawOverlay(); + await vi.advanceTimersByTimeAsync(1000); + + expect(reportEvent).not.toHaveBeenCalled(); + }); + + it("ignores ad frames once the player is back on the menu", async () => { + promos.destroyBottomRail(); + await vi.advanceTimersByTimeAsync(0); + restoreMenuChrome(); + + drawOverlay(); + await vi.advanceTimersByTimeAsync(1000); + + expect(reportEvent).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/client/Telemetry.test.ts b/tests/client/Telemetry.test.ts index 91f1e022b68..0dd46670aa5 100644 --- a/tests/client/Telemetry.test.ts +++ b/tests/client/Telemetry.test.ts @@ -328,6 +328,7 @@ describe("Telemetry", () => { expect(beforeSend(event("bottom_rail_in_game"))).not.toBeNull(); } expect(beforeSend(event("bottom_rail_in_game"))).toBeNull(); + expect(beforeSend(event("ad_frame_in_game"))).not.toBeNull(); }); it("sends everything from every session on staging", async () => {