Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add config to allow excluding iframes from the ttvc measurement, include by default #87

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/inViewportImageObserver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {Logger} from './util/logger';
import {CONFIG} from './util/constants';

/**
* Modeled after IntersectionObserver and MutationObserver, this Image observer
Expand Down Expand Up @@ -33,6 +34,9 @@ export class InViewportImageObserver {
private intersectionObserverCallback = (entries: IntersectionObserverEntry[]) => {
entries.forEach((entry) => {
const img = entry.target as HTMLImageElement | HTMLIFrameElement;
if (CONFIG.EXCLUDE_IFRAME && entry.target instanceof HTMLIFrameElement) {
return;
}
const timestamp = this.imageLoadTimes.get(img);
if (entry.isIntersecting && timestamp != null) {
Logger.info('InViewportImageObserver.callback()', '::', 'timestamp =', timestamp);
Expand All @@ -44,7 +48,7 @@ export class InViewportImageObserver {
};

private handleLoadOrErrorEvent = (event: Event) => {
if (event.target instanceof HTMLImageElement || event.target instanceof HTMLIFrameElement) {
if (event.target instanceof HTMLImageElement || (!CONFIG.EXCLUDE_IFRAME && event.target instanceof HTMLIFrameElement)) {
Logger.debug('InViewportImageObserver.handleLoadOrErrorEvent()', '::', 'event =', event);
this.imageLoadTimes.set(event.target, event.timeStamp);
this.intersectionObserver.observe(event.target);
Expand Down
5 changes: 5 additions & 0 deletions src/inViewportMutationObserver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {Logger} from './util/logger';
import {CONFIG} from './util/constants';

export type InViewportMutationObserverCallback = (mutation: TimestampedMutationRecord) => void;
export type TimestampedMutationRecord = MutationRecord & {timestamp?: number};
Expand Down Expand Up @@ -69,6 +70,10 @@ export class InViewportMutationObserver {
return;
}

if (CONFIG.EXCLUDE_IFRAME && target instanceof HTMLIFrameElement) {
return;
}

switch (mutation.type) {
case 'childList':
mutation.addedNodes.forEach((node) => {
Expand Down
4 changes: 4 additions & 0 deletions src/util/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export type TtvcOptions = {
debug?: boolean;
idleTimeout?: number;
networkTimeout?: number;
excludeIframe?: boolean;
};

/** ttvc configuration values set during initialization */
Expand All @@ -19,10 +20,13 @@ export const CONFIG = {
* If NETWORK_TIMEOUT is set to 0, disable this feature.
*/
NETWORK_TIMEOUT: 60000,

EXCLUDE_IFRAME: false,
};

export const setConfig = (options?: TtvcOptions) => {
if (options?.debug) CONFIG.DEBUG = options.debug;
if (options?.idleTimeout) CONFIG.IDLE_TIMEOUT = options.idleTimeout;
if (options?.networkTimeout) CONFIG.NETWORK_TIMEOUT = options.networkTimeout;
if (options?.excludeIframe) CONFIG.EXCLUDE_IFRAME = options.excludeIframe;
};
18 changes: 18 additions & 0 deletions test/e2e/iframe4/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<head>
<script src="/dist/index.min.js"></script>
<script src="/analytics-no-iframe.js"></script>
</head>

<body>
<h1 id="h1">Hello world!</h1>

<script>
// <iframe src="/stub.html?delay=500"></iframe>
const iframe = document.createElement('iframe');
iframe.src = '/stub.html?delay=500';


// append iframe after "load" event fires
window.addEventListener('load', () => document.body.appendChild(iframe));
</script>
</body>
20 changes: 20 additions & 0 deletions test/e2e/iframe4/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {test, expect} from '@playwright/test';

import {getEntriesAndErrors} from '../../util/entries';

const PAGELOAD_DELAY = 200;
const IFRAME_DELAY = 500;

test.describe('TTVC', () => {
test('a static document with an iframe', async ({page}) => {
await page.goto(`/test/iframe4?delay=${PAGELOAD_DELAY}`, {
waitUntil: 'networkidle',
});

const {entries} = await getEntriesAndErrors(page);

expect(entries.length).toBe(1);
expect(entries[0].duration).toBeGreaterThanOrEqual(PAGELOAD_DELAY);
expect(entries[0].duration).toBeLessThan(PAGELOAD_DELAY + IFRAME_DELAY);
});
});
23 changes: 23 additions & 0 deletions test/server/public/analytics-no-iframe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// use window.entries and window.errors to communicate between browser and test runner processes
window.entries = [];
window.errors = [];

// patch window.fetch
const old2Fetch = window.fetch;
window.fetch = (...args) => {
TTVC.incrementAjaxCount();
return old2Fetch(...args).finally(TTVC.decrementAjaxCount);
};

TTVC.init({debug: true, networkTimeout: window.NETWORK_TIMEOUT ?? 3000, excludeIframe: true});

TTVC.onTTVC(
(measurement) => {
console.log('TTVC:SUCCESS', measurement);
window.entries.push(measurement);
},
(error) => {
console.log('TTVC:ERROR', error);
window.errors.push(error);
}
);