@guardian/ophan-tracker-js
v5.1.2
Published
Browser JavaScript client for Ophan.
Keywords
Readme
Using Ophan Tracker JS
Browser JavaScript client for Ophan.
Install
$ npm install @guardian/ophan-tracker-jsUsage
Tracker JS is available as both an NPM package and a CDN distribution.
NPM Package
The NPM package uses a unified entry point that supports multiple platforms. Import it eagerly and call init() once for your platform before calling any other tracker method. The platform defaults to ng when omitted or unrecognised at runtime.
NPM Supported Platforms
ng(short for next-gen) for theguardian.commanage-my-accountfor manage.theguardian.comsupportfor support.theguardian.com
Default behaviour
The default entry point for the library is @guardian/ophan-tracker-js, which resolves to NPM-dist/index.js. Calling init() starts the tracker for the chosen platform and sends the initial page-view event. Use record() for additional events. Use sendInitialEvent() only when you intentionally need a new page-view event, for example after a single-page app route change.
If a tracker method is called before init() in a browser context, the method warns and does not send the event. In server-side rendering or other non-browser contexts, tracker methods return without touching browser globals.
CDN Distribution
The CDN version provides individual entry points for specific use cases, available at https://j.ophan.co.uk/. These entry points initialise themselves for their historical platform and are kept for existing CDN consumers:
contribution.js- Contribution trackingembed.js- For embedded contentfb-instant.js- For Facebook Instant Articlesholidays.js- Guardian Holidayshttp-status.js- HTTP status page trackinginteractive.js- For Guardian interactivesjobs.js- For Guardian Jobs sitejobs-courses.js- For Guardian Jobs courses sitemembership.js- For Guardian membership (old site)ng.js- For theguardian.comr2.js- Legacy R2 platform trackingsmart-news.js- SmartNews platform trackingwitness.js- GuardianWitness tracking
Plain <script src> (IIFE) build
The AMD (ophan/*.js) and SystemJS (*.js) CDN builds both require a module
loader on the page. For consumers that have no module loader and no bundler
— e.g. the Salesforce-hosted Help Centre — there is a self-executing IIFE build:
help-centre.iife.js- Exposes explicit Help Centre page-view tracking atwindow.guardian.ophanwithout sending anything when the script loads.
<script src="https://j.ophan.co.uk/help-centre.iife.js"></script>
<script>
// Call only when the Help Centre considers this to be a page view.
window.guardian.ophan.sendInitialPageview();
</script>You can see example usage of the library on theguardian.com here
Import and initialise the library:
The library should be imported and initialised eagerly (non-lazily) to ensure proper initialisation. The exact syntax may vary depending on your build tool or environment.
import { init, record } from '@guardian/ophan-tracker-js'; // Initialise for your platform. This sends the initial page-view event. init('ng'); // or 'manage-my-account' or 'support'Send Tracking Events with
record():record({ edition: 'UK', });
Usage with TypeScript
The package exports TypeScript declarations, declaration maps, and source files. Editors should let you click through from record() to EventPayload, ComponentEvent, Product, and the related union types in src/types/event.ts and the neighbouring type files.
When you pass an object literal to record(), TypeScript will reject unknown top-level fields and invalid nested values such as unsupported component actions, component types, products, or editions. If you need to add a new event type or property, update the tracker-js types and the downstream Ophan model deliberately.
Example Usage
import {
getViewId,
init,
record,
sendInitialEvent,
} from '@guardian/ophan-tracker-js';
import type {
EventPayload,
Product,
ComponentEvent,
AbTest,
} from '@guardian/ophan-tracker-js';
// Initialise the library for your platform. This sends the initial page-view event.
init('ng'); // or 'manage-my-account' or 'support'
const exampleProduct: Product = 'APP_PREMIUM_TIER';
const exampleAbTest: AbTest = {
name: 'myAbTest',
variant: 'variant',
campaignCodes: ['code1', 'code2'],
};
const componentV2 = {
componentType: 'ACQUISITIONS_BUTTON',
id: 'component-id',
products: [exampleProduct],
campaignCode: 'campaign-code',
labels: ['label1', 'label2'],
};
const componentEvent: ComponentEvent = {
component: componentV2,
action: 'CLICK',
value: 'some-value',
id: 'event-id',
abTest: exampleAbTest,
targetingAbTest: exampleAbTest,
};
const payload: EventPayload = {
componentEvent: componentEvent,
};
record(payload);
const currentViewId = getViewId();
// Use sendInitialEvent() only when intentionally creating a new page view,
// for example after a single-page app route change.
sendInitialEvent();getViewId() and getPageViewId() return the current live page view ID. The default export also exposes viewId and pageViewId as getters for compatibility with object-style consumers.
If you would like to add a new event type or event property which does not exist, please contact the Ophan team.
Sending events straight to the backend
Please consult with the Ophan team if you wish to do this.
The backend of tracker exposes two endpoints, img/1 which takes in page view events, and img/2 which takes in all other events. For events sent to the img/2 endpoint, a page view event MUST also be created via the img/1. Further down the Ophan and Datatech pipeline, events with the same page view ID are tied together for ease of querying and data analysis. Therefore, a page view event must be present.
Developing Ophan Tracker JS
The library is implemented using both Javascript and TypeScript, with the source code located in the src directory and its subdirectories. The project is set up to include both TypeScript (.ts) and JavaScript (.js) files, allowing for a mix of both languages in the library's implementation.
Typescript interfaces and types are developed in the src/types folder.
The TypeScript compiler is configured to generate compiled JavaScript files and corresponding declaration files (.d.ts) in the NPM-dist directory. The declaration files provide type information for the library's public API, and declaration maps point editors back to the source files.
Compile
.../ophan/tracker-js $ npm run build-for-npmType checks
.../ophan/tracker-js $ npm run test:typesProxy tracker-js:
Install dependencies
$ brew install lighttpd .../ophan/tracker-js $ npm installIn another terminal window:
.../ophan/tracker-js $ lighttpd -f lighttpd.conf -DInstall FoxyProxy (https://getfoxyproxy.org/downloads/) in your browser and create a rule that forces j.ophan.co.uk to localhost 8000. (For me FoxyProxy needed a few switches on and off before it decided to start talking to lighttpd.)
In another terminal window, start a server that is running the Guardian frontend
Navigate to where you are running the Guardian locally (e.g. https://localhost:9000/uk)
Ensure FoxyProxy is enabled
Develop with pleasure
Publish
Two formats for release
When you make a change to Tracker JS, you must release on both these systems:
NPM
We use changesets for automated publishing of the NPM package:
Add a changeset, run the following command and follow the instructions
.../ophan/tracker-js $ npx changesetWhen you raise a PR, the changeset bot won’t correctly see that you have included a changeset – it only checks for the .changesets folder in the root of the repository, whereas we have it in a subdirectory. Don’t worry.
When the PR is merged, the
changesetsgithub action will create a new PR, example here. On merging this generated PR, the action will publish to NPM. (This checks the subdirectory correctly.)
S3 Bucket
- https://j.ophan.co.uk/ - CDN/S3, deployed through RiffRaff and used by some Guardian sites like https://jobs.theguardian.com/. An advantage of this approach is that sites using it immediately get Tracker JS updates, without developer intervention.
Rollup
The generated files from Rollup (using the build-for-cdn script in package.json) are only used for publishing to the CDN to use SystemJS / AMD
Post publish
Post publish it would be good practice to inform the teams using Tracker-JS about the update.
See the google doc for a list of teams depending on tracker-js.
If the change to tracker-js is small, we could raise a quick PR in the relevant repo and ask the team to review it.
