Skip to content
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
15 changes: 10 additions & 5 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -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"
10 changes: 7 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)

Expand Down
60 changes: 59 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<head>` section of every page, making sure to replace `<YOUR APP ID>` with your actual App ID:

```html
<script async
<script
async
src="https://cdn.telemetrydeck.com/websdk/telemetrydeck.min.js"
data-app-id="<YOUR APP ID>"
></script>
```

## 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
<script
async
src="https://cdn.telemetrydeck.com/websdk/telemetrydeck.min.js"
data-app-id="<YOUR APP ID>"
data-page-engagement="false"
></script>
```

#### 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.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
17 changes: 17 additions & 0 deletions src/config.mjs
Original file line number Diff line number Diff line change
@@ -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;
91 changes: 91 additions & 0 deletions src/page-engagement.mjs
Original file line number Diff line number Diff line change
@@ -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);
}
63 changes: 63 additions & 0 deletions src/send.mjs
Original file line number Diff line number Diff line change
@@ -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(() => {});
}
36 changes: 6 additions & 30 deletions src/telemetrydeck.mjs
Original file line number Diff line number Diff line change
@@ -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),
});
9 changes: 9 additions & 0 deletions tests/dummys/async-request.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!DOCTYPE html>
<meta charset="UTF-8" />
<title>Async Request</title>
<script
async
data-app-id="AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"
src="http://127.0.0.1:3001/telemetrydeck.min.js"
></script>
<h1>Async Request</h1>
24 changes: 24 additions & 0 deletions tests/dummys/page-engagement-disabled.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Page Engagement Disabled</title>
<style>
body,
h1,
p {
margin: 0;
}
body {
min-height: 400vh;
}
</style>
<script
defer
data-app-id="AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"
data-page-engagement="false"
src="http://127.0.0.1:3001/telemetrydeck.min.js"
></script>
<h1>Page Engagement Disabled</h1>
<p>
<a data-testid="next-page-link" href="/simple-request.html">Simple Request</a>
</p>
23 changes: 23 additions & 0 deletions tests/dummys/page-engagement.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Page Engagement</title>
<style>
body,
h1,
p {
margin: 0;
}
body {
min-height: 400vh;
}
</style>
<script
defer
data-app-id="AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"
src="http://127.0.0.1:3001/telemetrydeck.min.js"
></script>
<h1>Page Engagement</h1>
<p>
<a data-testid="next-page-link" href="/simple-request.html">Simple Request</a>
</p>
Loading
Loading