diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5990d9c..54b5236 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,11 +1,16 @@ -# To get started with Dependabot version updates, you'll need to specify which -# package ecosystems to update and where the package manifests are located. -# Please see the documentation for all configuration options: +# Dependabot version updates. Documentation for all configuration options: # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file version: 2 updates: - - package-ecosystem: "" # See documentation for possible values - directory: "/" # Location of package manifests + # package.json / pnpm-lock.yaml (Dependabot handles pnpm under the npm ecosystem) + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + + # Actions used in .github/workflows + - package-ecosystem: "github-actions" + directory: "/" schedule: interval: "weekly" diff --git a/CHANGELOG.md b/CHANGELOG.md index d18639d..99466e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,12 @@ +## v3.0.0 (unreleased) +#### :rocket: Enhancement +* Send a `TelemetryDeck.Web.pageLeave` event when a page is hidden or unloaded, carrying scroll depth and engaged time as `TelemetryDeck.PageEngagement.*` parameters. On by default, opt out with `data-page-engagement="false"`. +* Send events to the Web events v3 endpoint (`/v3/w/`) as flat events. Parameters sit at the top level of the event instead of inside a `payload` object and keep their JSON types, so numbers such as scroll depth arrive as numbers. `isTestMode` is always sent, as the string `"true"` or `"false"`. - - - +#### :boom: Breaking Change +* The default `data-api` is now `https://nom.telemetrydeck.com/v3/w/`. A custom `data-api` must point at a Web events v3 endpoint; the `/v2/w/` endpoint does not accept the new request format. +* `telemetryClientVersion` is no longer sent. Use `TelemetryDeck.SDK.name`, `TelemetryDeck.SDK.version` or `TelemetryDeck.SDK.nameAndVersion` instead. ## v1.0.5 (2022-05-27) diff --git a/README.md b/README.md index 4de778f..7bd03cf 100644 --- a/README.md +++ b/README.md @@ -15,12 +15,70 @@ Note that if you are a programmer working on a node package based JavaScript app Once you have your App ID, edit the source code of your website and add the following code snippet to the `` section of every page, making sure to replace `` with your actual App ID: ```html - ``` +## Events + +The SDK sends two events per page load to the Web events v3 endpoint (`https://nom.telemetrydeck.com/v3/w/`). Each request carries one flat event; every parameter sits at the top level of the event and keeps its JSON type. The ingest server fills in `receivedAt` and the default `type` (`pageview`), and derives browser, system, location and campaign data from the request itself. + +### `pageview` + +Sent as soon as the script loads. Contains the page `url`, the `referrer`, the browser `locale`, `isTestMode` (`"true"` or `"false"`) and the SDK version (`TelemetryDeck.SDK.name`, `TelemetryDeck.SDK.version` and `TelemetryDeck.SDK.nameAndVersion`). + +### `TelemetryDeck.Web.pageLeave` + +Sent once per page load, the first time the page is hidden or unloaded (tab switched, tab closed, navigation to another page). It reports how far visitors scrolled and how long the page was actually visible, as top-level parameters of the event: + +| Parameter | Value | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| `TelemetryDeck.PageEngagement.scrollDepth` | Deepest point of the page that was in view, in percent (`0`–`100`). A page that fits the viewport counts as `100`. | +| `TelemetryDeck.PageEngagement.scrollDepthMilestone` | The highest milestone reached: `"0"`, `"25"`, `"50"`, `"75"` or `"100"`. Handy as a dimension for donut charts and funnels. | +| `TelemetryDeck.PageEngagement.engagedSeconds` | Seconds the page was visible in the foreground, rounded to whole seconds. | + +The event carries the same `url` and `referrer` as the `pageview`, so both can be joined per page. + +Page engagement tracking is on by default. To turn it off, add `data-page-engagement="false"` to the script tag: + +```html + +``` + +#### Example: average scroll depth per page + +```json +{ + "queryType": "groupBy", + "granularity": "all", + "filter": { + "type": "selector", + "dimension": "type", + "value": "TelemetryDeck.Web.pageLeave" + }, + "dimensions": [{ "type": "default", "dimension": "url", "outputName": "URL" }], + "aggregations": [ + { + "type": "doubleMean", + "name": "Average Scroll Depth", + "fieldName": "TelemetryDeck.PageEngagement.scrollDepth" + } + ] +} +``` + +## Testing locally + +Events sent from `localhost`, `127.0.0.1` or `file:` URLs are marked as test mode automatically. You can force test mode with `data-is-test-mode="true"` and point the SDK at a different ingest server with `data-api` (for example `data-api="http://localhost:8080/v3/w/"` for a locally running ingest server). + ## 📱 You need an App ID Every application and website registered to TelemetryDeck has its own unique ID that we use to assign incoming signals to the correct app. To get started, create a new app in the TelemetryDeck UI and copy its ID. diff --git a/package.json b/package.json index 39e19ee..a4fcaec 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@telemetrydeck/web", - "version": "1.1.0", + "version": "3.0.0", "description": "Send analytics signals to TelemetryDeck", "main": "dist/telemetrydeck.js", "module": "dist/telemetrydeck.mjs", diff --git a/src/config.mjs b/src/config.mjs new file mode 100644 index 0000000..26032d9 --- /dev/null +++ b/src/config.mjs @@ -0,0 +1,17 @@ +// Read once at load time: `document.currentScript` is only available while the +// script element is executing, so this module must be evaluated first. +const script = document.currentScript; +const dataset = script ? script.dataset : {}; +const { location = {} } = globalThis; + +export const appId = dataset.appId; +export const api = dataset.api ?? 'https://nom.telemetrydeck.com/v3/w/'; + +// Page engagement (scroll depth, engaged time) is on by default; opt out with +// `data-page-engagement="false"`. +export const pageEngagement = dataset.pageEngagement !== 'false'; + +export const isTestMode = + dataset.isTestMode === 'true' || + /^localhost$|^127(\.\d+){0,2}\.\d+$|^\[::1?]$/.test(location.hostname) || + 'file:' === location.protocol; diff --git a/src/page-engagement.mjs b/src/page-engagement.mjs new file mode 100644 index 0000000..fb50baf --- /dev/null +++ b/src/page-engagement.mjs @@ -0,0 +1,91 @@ +import { buildEvent, sendBeacon } from './send.mjs'; + +const MILESTONES = [100, 75, 50, 25]; + +// Percentage of the page that has been in view so far, 0–100. A page that fits +// the viewport counts as 100. +function measureScrollDepth() { + const { documentElement, body } = document; + const scrollHeight = Math.max(documentElement.scrollHeight, body ? body.scrollHeight : 0); + + if (!scrollHeight) { + return 100; + } + + const bottom = window.scrollY + window.innerHeight; + + return Math.min(100, Math.max(0, Math.round((bottom / scrollHeight) * 100))); +} + +function milestone(depth) { + return String(MILESTONES.find((value) => depth >= value) ?? 0); +} + +export function trackPageEngagement() { + let maxDepth = 0; + let engagedMilliseconds = 0; + let visibleSince = document.visibilityState === 'visible' ? performance.now() : undefined; + let frame; + let sent = false; + + const update = () => { + frame = undefined; + maxDepth = Math.max(maxDepth, measureScrollDepth()); + }; + + // Coalesce scroll events so layout is read at most once per frame. + const scheduleUpdate = () => { + if (frame === undefined) { + frame = requestAnimationFrame(update); + } + }; + + const pause = () => { + if (visibleSince !== undefined) { + engagedMilliseconds += performance.now() - visibleSince; + visibleSince = undefined; + } + }; + + const resume = () => { + if (visibleSince === undefined) { + visibleSince = performance.now(); + } + }; + + // Sent exactly once, the first time the page is hidden or unloaded. + const leave = () => { + if (sent) { + return; + } + + sent = true; + pause(); + update(); + + removeEventListener('scroll', scheduleUpdate); + removeEventListener('resize', scheduleUpdate); + + sendBeacon( + buildEvent({ + type: 'TelemetryDeck.Web.pageLeave', + 'TelemetryDeck.PageEngagement.scrollDepth': maxDepth, + 'TelemetryDeck.PageEngagement.scrollDepthMilestone': milestone(maxDepth), + 'TelemetryDeck.PageEngagement.engagedSeconds': Math.round(engagedMilliseconds / 1000), + }) + ); + }; + + const onVisibilityChange = () => { + if (document.visibilityState === 'hidden') { + leave(); + } else { + resume(); + } + }; + + addEventListener('scroll', scheduleUpdate, { passive: true }); + addEventListener('resize', scheduleUpdate, { passive: true }); + document.addEventListener('visibilitychange', onVisibilityChange); + addEventListener('pagehide', leave); +} diff --git a/src/send.mjs b/src/send.mjs new file mode 100644 index 0000000..559040c --- /dev/null +++ b/src/send.mjs @@ -0,0 +1,63 @@ +import { version } from '../package.json'; +import { api, appId, isTestMode } from './config.mjs'; + +const { location = {} } = globalThis; + +// Captured once so that every event of this page load reports the same URL. +const url = location.href; + +const sdkName = 'WebSDK'; +const sdkNameAndVersion = `${sdkName} ${version}`; + +// Web events v3 are flat: every parameter sits at the top level of the event +// and may be any JSON value, not only strings. The ingest server fills in +// `receivedAt` and `type` (`pageview`) when they are missing and derives +// browser, system, location and campaign data itself. +export function buildEvent(extra = {}) { + return { + appID: appId, + url, + referrer: document.referrer, + locale: navigator.language, + // A string rather than a boolean, matching what every other SDK sends. + isTestMode: isTestMode ? 'true' : 'false', + 'TelemetryDeck.SDK.name': sdkName, + 'TelemetryDeck.SDK.version': version, + 'TelemetryDeck.SDK.nameAndVersion': sdkNameAndVersion, + ...extra, + }; +} + +// The endpoint takes exactly one event per request. +function serialize(event) { + return JSON.stringify(event); +} + +export function send(event) { + return fetch(api, { + method: 'POST', + mode: 'cors', + headers: { + 'Content-Type': 'application/json', + }, + body: serialize(event), + }); +} + +// Used while the page is being hidden or unloaded. The body is sent as a plain +// string (`text/plain`), which needs no CORS preflight and therefore survives +// the unload; the ingest server parses JSON regardless of the content type. +export function sendBeacon(event) { + const data = serialize(event); + + if (navigator.sendBeacon && navigator.sendBeacon(api, data)) { + return; + } + + fetch(api, { + method: 'POST', + mode: 'cors', + keepalive: true, + body: data, + }).catch(() => {}); +} diff --git a/src/telemetrydeck.mjs b/src/telemetrydeck.mjs index 9c64ba2..9c09518 100644 --- a/src/telemetrydeck.mjs +++ b/src/telemetrydeck.mjs @@ -1,36 +1,12 @@ -import { version } from '../package.json'; +import { appId, pageEngagement } from './config.mjs'; import { assert } from './utils/assert.mjs'; - -const script = document.currentScript; -const appId = script.dataset.appId; -const isTestMode = script.dataset.isTestMode === 'true'; -const api = script.dataset.api ?? 'https://nom.telemetrydeck.com/v2/w/'; -const { language: locale } = navigator; -const { location = {} } = globalThis; +import { buildEvent, send } from './send.mjs'; +import { trackPageEngagement } from './page-engagement.mjs'; assert(appId, '"data-app-id" missing'); -const body = { - appID: appId, - url: location.href, - referrer: document.referrer, - telemetryClientVersion: `WebSDK ${version}`, - locale, -}; +send(buildEvent()); -if ( - isTestMode || - /^localhost$|^127(\.\d+){0,2}\.\d+$|^\[::1?]$/.test(location.hostname) || - 'file:' === location.protocol -) { - body.isTestMode = true; +if (pageEngagement) { + trackPageEngagement(); } - -fetch(api, { - method: 'POST', - mode: 'cors', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(body), -}); diff --git a/tests/dummys/async-request.html b/tests/dummys/async-request.html new file mode 100644 index 0000000..606e19b --- /dev/null +++ b/tests/dummys/async-request.html @@ -0,0 +1,9 @@ + + +Async Request + +

Async Request

diff --git a/tests/dummys/page-engagement-disabled.html b/tests/dummys/page-engagement-disabled.html new file mode 100644 index 0000000..c610a0c --- /dev/null +++ b/tests/dummys/page-engagement-disabled.html @@ -0,0 +1,24 @@ + + + +Page Engagement Disabled + + +

Page Engagement Disabled

+

+ Simple Request +

diff --git a/tests/dummys/page-engagement.html b/tests/dummys/page-engagement.html new file mode 100644 index 0000000..17e9f79 --- /dev/null +++ b/tests/dummys/page-engagement.html @@ -0,0 +1,23 @@ + + + +Page Engagement + + +

Page Engagement

+

+ Simple Request +

diff --git a/tests/dummys/request-with-referrer.html b/tests/dummys/request-with-referrer.html index 4681bfc..42bc239 100644 --- a/tests/dummys/request-with-referrer.html +++ b/tests/dummys/request-with-referrer.html @@ -1,10 +1,10 @@ - + Request with Referrer

Request with Referrer

diff --git a/tests/sdk.spec.js b/tests/sdk.spec.js index 6c68894..0eb2975 100644 --- a/tests/sdk.spec.js +++ b/tests/sdk.spec.js @@ -1,29 +1,78 @@ // @ts-check const { test, expect } = require('@playwright/test'); +const API = 'https://nom.telemetrydeck.com/v3/w/'; +const APP_ID = 'AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE'; +const PAGE_LEAVE = 'TelemetryDeck.Web.pageLeave'; + +// Every request carries exactly one flat event. +const eventOf = (request) => request.postDataJSON(); + +const isPageLeave = (request) => request.url() === API && eventOf(request)['type'] === PAGE_LEAVE; + +const isPageview = (request) => request.url() === API && eventOf(request)['type'] === undefined; + test.beforeEach(async ({ page }) => { - await page.route('https://nom.telemetrydeck.com/v2/w/', async (route) => { + await page.route(API, async (route) => { await route.fulfill({ - body: 'Likely OK', + body: 'OK', }); }); }); test('Loads and calls TelemetryDeck Web SDK', async ({ page }) => { - const requestPromise = page.waitForRequest('https://nom.telemetrydeck.com/v2/w/'); + const requestPromise = page.waitForRequest(API); await page.goto('/simple-request.html'); const request = await requestPromise; + const event = eventOf(request); expect(request.method()).toBe('POST'); - expect(request.postDataJSON()).toHaveProperty('url'); - expect(request.postDataJSON()).toHaveProperty('appID'); - expect(request.postDataJSON()['url']).toBe('http://127.0.0.1:3000/simple-request.html'); - expect(request.postDataJSON()['appID']).toBe('AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE'); + expect(request.headers()['content-type']).toBe('application/json'); + expect(Array.isArray(event)).toBe(false); + expect(event).toHaveProperty('url'); + expect(event).toHaveProperty('appID'); + expect(event['url']).toBe('http://127.0.0.1:3000/simple-request.html'); + expect(event['appID']).toBe(APP_ID); + expect(event['type']).toBeUndefined(); + expect(event['receivedAt']).toBeUndefined(); + expect(event['payload']).toBeUndefined(); + expect(event['locale']).toEqual(expect.any(String)); + expect(event['telemetryClientVersion']).toBeUndefined(); + expect(event['TelemetryDeck.SDK.name']).toBe('WebSDK'); + expect(event['TelemetryDeck.SDK.version']).toMatch(/^\d+\.\d+\.\d+/); + expect(event['TelemetryDeck.SDK.nameAndVersion']).toBe( + `WebSDK ${event['TelemetryDeck.SDK.version']}` + ); +}); + +test('Marks events from 127.0.0.1 as test mode, as a string', async ({ page }) => { + const requestPromise = page.waitForRequest(isPageview); + + await page.goto('/simple-request.html'); + + const event = eventOf(await requestPromise); + + expect(event['isTestMode']).toBe('true'); +}); + +test('Works when the script tag is loaded with `async`', async ({ page }) => { + const pageviewPromise = page.waitForRequest(isPageview); + await page.goto('/async-request.html'); + const pageview = eventOf(await pageviewPromise); + + expect(pageview['url']).toBe('http://127.0.0.1:3000/async-request.html'); + expect(pageview['appID']).toBe(APP_ID); + + const pageLeavePromise = page.waitForRequest(isPageLeave); + await page.goto('/missing-app-id.html'); + const pageLeave = eventOf(await pageLeavePromise); + + expect(pageLeave['url']).toBe('http://127.0.0.1:3000/async-request.html'); }); -test('Script fails if `data-test-app-id` is not set', async ({ page }) => { +test('Script fails if `data-app-id` is not set', async ({ page }) => { const exceptions = []; page.on('pageerror', async (exception) => { @@ -35,14 +84,14 @@ test('Script fails if `data-test-app-id` is not set', async ({ page }) => { expect(exceptions).toEqual([new Error('TelemetryDeck: "data-app-id" missing')]); }); -test('Script fails if `data-test-app-id` is empty', async ({ page }) => { +test('Script fails if `data-app-id` is empty', async ({ page }) => { const exceptions = []; page.on('pageerror', async (exception) => { exceptions.push(exception); }); - await page.goto('/missing-app-id.html'); + await page.goto('/empty-app-id.html'); expect(exceptions).toEqual([new Error('TelemetryDeck: "data-app-id" missing')]); }); @@ -50,19 +99,114 @@ test('Script fails if `data-test-app-id` is empty', async ({ page }) => { test('Referrer is set after navigating from one page to another', async ({ page }) => { await page.goto('/request-with-referrer.html'); - const requestPromise = page.waitForRequest('https://nom.telemetrydeck.com/v2/w/'); + const requestPromise = page.waitForRequest( + (request) => + isPageview(request) && eventOf(request)['url'] === 'http://127.0.0.1:3000/simple-request.html' + ); await page.getByTestId('next-page-link').click(); const request = await requestPromise; + const event = eventOf(request); expect(request.method()).toBe('POST'); - expect(request.postDataJSON()).toHaveProperty('url'); - expect(request.postDataJSON()).toHaveProperty('appID'); - expect(request.postDataJSON()).toHaveProperty('referrer'); - expect(request.postDataJSON()['url']).toBe('http://127.0.0.1:3000/simple-request.html'); - expect(request.postDataJSON()['appID']).toBe('AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE'); - expect(request.postDataJSON()['referrer']).toBe( - 'http://127.0.0.1:3000/request-with-referrer.html' + expect(event).toHaveProperty('url'); + expect(event).toHaveProperty('appID'); + expect(event).toHaveProperty('referrer'); + expect(event['url']).toBe('http://127.0.0.1:3000/simple-request.html'); + expect(event['appID']).toBe(APP_ID); + expect(event['referrer']).toBe('http://127.0.0.1:3000/request-with-referrer.html'); +}); + +test('Sends a page leave event with scroll depth and engaged time', async ({ page }) => { + const pageLeaveRequests = []; + page.on('request', (request) => { + if (isPageLeave(request)) { + pageLeaveRequests.push(request); + } + }); + + const pageviewPromise = page.waitForRequest(isPageview); + await page.goto('/page-engagement.html'); + await pageviewPromise; + + // Scroll 1.2 viewport heights down on a page that is four viewports tall, + // so 2.2 of 4 viewports have been seen: 55%. Staying clear of the 50% + // boundary keeps the milestone assertion stable across browsers. + await page.evaluate(() => window.scrollTo(0, window.innerHeight * 1.2)); + // Stay on the page for a little over a second so engaged time reaches 1s. + await page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 1100))); + + const pageLeavePromise = page.waitForRequest(isPageLeave); + const nextPageviewPromise = page.waitForRequest( + (request) => + isPageview(request) && eventOf(request)['url'] === 'http://127.0.0.1:3000/simple-request.html' ); + + await page.getByTestId('next-page-link').click(); + + const request = await pageLeavePromise; + await nextPageviewPromise; + + const event = eventOf(request); + + expect(request.method()).toBe('POST'); + expect(event['appID']).toBe(APP_ID); + expect(event['url']).toBe('http://127.0.0.1:3000/page-engagement.html'); + expect(event['type']).toBe(PAGE_LEAVE); + // Page engagement parameters sit at the top level of the flat event, and + // the numeric ones stay numbers. + expect(event['payload']).toBeUndefined(); + expect(event['TelemetryDeck.PageEngagement.scrollDepth']).toBeGreaterThanOrEqual(52); + expect(event['TelemetryDeck.PageEngagement.scrollDepth']).toBeLessThanOrEqual(58); + expect(event['TelemetryDeck.PageEngagement.scrollDepthMilestone']).toBe('50'); + expect(event['TelemetryDeck.PageEngagement.engagedSeconds']).toBeGreaterThanOrEqual(1); + expect(typeof event['TelemetryDeck.PageEngagement.engagedSeconds']).toBe('number'); + + // visibilitychange and pagehide both fire on navigation; only one event is sent. + expect(pageLeaveRequests).toHaveLength(1); +}); + +test('A page that fits the viewport reports a scroll depth of 100', async ({ page }) => { + const pageviewPromise = page.waitForRequest(isPageview); + await page.goto('/simple-request.html'); + await pageviewPromise; + + const pageLeavePromise = page.waitForRequest(isPageLeave); + + await page.goto('/missing-app-id.html'); + + const event = eventOf(await pageLeavePromise); + + expect(event['url']).toBe('http://127.0.0.1:3000/simple-request.html'); + expect(event['TelemetryDeck.PageEngagement.scrollDepth']).toBe(100); + expect(event['TelemetryDeck.PageEngagement.scrollDepthMilestone']).toBe('100'); +}); + +test('No page leave event is sent when `data-page-engagement` is "false"', async ({ page }) => { + const events = []; + page.on('request', (request) => { + if (request.url() === API) { + events.push(eventOf(request)); + } + }); + + const pageviewPromise = page.waitForRequest(isPageview); + await page.goto('/page-engagement-disabled.html'); + await pageviewPromise; + + await page.evaluate(() => window.scrollTo(0, window.innerHeight)); + + const nextPageviewPromise = page.waitForRequest( + (request) => + isPageview(request) && eventOf(request)['url'] === 'http://127.0.0.1:3000/simple-request.html' + ); + + await page.getByTestId('next-page-link').click(); + await nextPageviewPromise; + + expect(events.filter((event) => event['type'] === PAGE_LEAVE)).toHaveLength(0); + expect( + events.filter((event) => event['url'] === 'http://127.0.0.1:3000/page-engagement-disabled.html') + ).toHaveLength(1); });