@guardian/ophan-tracker-js

中文文档
5.5.0发布于 2026/11/12TypeScriptES Module近 30 天下载 2.7万

Browser JavaScript client for Ophan.

原始使用文档
文档目录13 节
  1. Install
  2. Usage
  3. NPM Package
  4. CDN Distribution
  5. Usage with TypeScript
  6. Sending events straight to the backend
  7. Compile
  8. Type checks
  9. Testing
  10. Browser behaviour tests
  11. Publish
  12. Two formats for release
  13. Post publish

Using Ophan tracker-js

Browser JavaScript client for Ophan.

Install

$ npm install @guardian/ophan-tracker-js

Usage

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.com
  • manage-my-account for manage.theguardian.com
  • support for 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 tracking
  • embed.js - For embedded content
  • fb-instant.js - For Facebook Instant Articles
  • holidays.js - Guardian Holidays
  • http-status.js - HTTP status page tracking
  • interactive.js - For Guardian interactives
  • jobs.js - For Guardian Jobs site
  • jobs-courses.js - For Guardian Jobs courses site
  • membership.js - For Guardian membership (old site)
  • ng.js - For theguardian.com
  • r2.js - Legacy R2 platform tracking
  • smart-news.js - SmartNews platform tracking
  • witness.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 at window.guardian.ophan without 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

  1. 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'
    
  2. 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-npm

Type checks

    .../ophan/tracker-js $ npm run test:types

Testing

Run unit tests with npm test. Browser behaviour tests are described below.

We decided not to adopt production shadow testing because running and isolating a second tracker in readers' browsers adds more JavaScript complexity and ongoing maintenance than the extra regression coverage justifies. The Ophan prototype and Dotcom integration are retained for reference.

Browser behaviour tests

The browser behaviour tests build the NPM package from the current source, load the Guardian front in headless Chrome and inject it as a self-contained script. This build from the current checkout is called the candidate, to distinguish it from the tracker-js version already deployed on the live page. The code under test comes from NPM-dist, the same build NPM consumers install; Rollup packages it into one script so Puppeteer can inject it. Requests are redirected to a non-routable test origin and inspected in the browser, so the tests do not send analytics to Ophan.

These tests validate the candidate's browser behaviour and outbound requests before release. OphTrack instead checks the deployed production tracker and verifies that pageviews pass through the complete Ophan ingestion pipeline into Elasticsearch.

npm run test:browser

Set GUARDIAN_FRONT_URL to test a different Guardian page. The default is https://www.theguardian.com/uk.

The tests suppress Ophan requests and disable the consent manager, but the production page can still contact other third parties. CI runs them for tracker-js pull requests; they can also be started manually from GitHub Actions.

Proxy tracker-js:

  1. Install dependencies

    $ brew install lighttpd
    .../ophan/tracker-js $ npm install
    
  2. In another terminal window:

    .../ophan/tracker-js $ lighttpd -f lighttpd.conf -D
    
  3. Install 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.)

  4. In another terminal window, start a server that is running the Guardian frontend

  5. Navigate to where you are running the Guardian locally (e.g. https://localhost:9000/uk)

  6. Ensure FoxyProxy is enabled

  7. 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:

  1. Add a changeset, run the following command and follow the instructions

    .../ophan/tracker-js $ npx changeset
    
  2. When 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.

  3. When the PR is merged, the changesets github 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

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.

版本与发布记录

@guardian/ophan-tracker-js 共发布 126 个版本,首次发布于 2023/11/08;过去 12 个月发布了 68 个版本。

版本发布日期距今
5.5.0latest2026/11/124 天前
5.4.02026/11/0412 天前
5.3.02026/11/0214 天前
0.0.0-canary-20261102144926canary2026/11/0214 天前
0.0.0-canary-202611021449082026/11/0214 天前
0.0.0-canary-202611021440022026/11/0214 天前

其他发布通道:next → 2.1.2-next.6,canary → 0.0.0-canary-20261102144926。

关于 @guardian/ophan-tracker-js 的常见问题

@guardian/ophan-tracker-js 是什么?

Browser JavaScript client for Ophan.

如何安装 @guardian/ophan-tracker-js?

在项目目录运行 npm install @guardian/ophan-tracker-js,或使用 pnpm add / yarn add / bun add。

@guardian/ophan-tracker-js 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@guardian/ophan-tracker-js 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@guardian/ophan-tracker-js 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@guardian/ophan-tracker-js 可以商用吗?

@guardian/ophan-tracker-js 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@guardian/ophan-tracker-js 的下载量有多少?

根据 npm 官方下载统计,@guardian/ophan-tracker-js 在 2026/10/17 – 2026/11/15 这 30 天内被下载 27,040 次,日均约 901 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@guardian/ophan-tracker-js 还在维护吗?

最新版本 5.5.0 发布于 2026/11/12(4 天前);至今共发布 126 个版本,其中过去 12 个月发布了 68 个;首次发布于 2023/11/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。