Getting started with page-lifecycle-tracker
Install page-lifecycle-tracker with npm or pnpm, read the Page Lifecycle API state of the page, and subscribe to each transition in ten lines of TypeScript.
Install the package
npm install page-lifecycle-trackerpnpm add page-lifecycle-trackerThe package is an ECMAScript module (ESM) with TypeScript types. It has no dependencies. Its package.json sets sideEffects to false, thus a bundler can remove the modules that your code does not import.
The tracker operates in a page. It reads document and window. In a worker, there is no document, thus getPageLifecycle() and createPageLifecycle() throw an error.
The first ten lines
import { getPageLifecycle, isVisibleState } from "page-lifecycle-tracker";
const lifecycle = getPageLifecycle();
console.log("The state at the start:", lifecycle.getState());
// A monitor: the default phase is "observe"
lifecycle.subscribe(({ from, to, trigger }) => console.log(`${from} to ${to} (${trigger})`));
// An exporter: it starts after all observe subscribers
lifecycle.subscribe(({ to }) => {
if (!isVisibleState(to)) exporter.flush();
}, { phase: "export" });The example does these steps:
getPageLifecycle()gives the tracker of the page. Its first use makes the tracker. Each later use, also from another library, gives the same tracker.getState()gives the current state:active,passive,hidden,frozenorterminated.- The first subscriber gets each transition, with the properties
from,to,triggerandtimestamp. - The second subscriber is in the
exportphase. It starts after allobservesubscribers of the same transition. Thus the values of the monitors are in the last export. isVisibleState()givestrueforactiveandpassive. When the page leaves these states, the exporter sends its data.
exporter.flush() is a function of your exporter. The OpenTelemetry recipe shows a real exporter.
Look at the state of this page
This site uses the library. The state of this page at this time is active. Click outside the browser window, then click in the page again. The state changes to passive and back to active.
The home page shows each transition of your visit on a diagram and a timeline.
NoteOne tracker for each page
Use getPageLifecycle() in a library. Then all libraries of the page share the transitions and the phases. createPageLifecycle() makes a private tracker, for example for a test.
Next steps
- Learn the states and their transitions.
- Read why an exporter subscribes in the export phase.
- Find the transitions of a measurement window with marks.
- Read the API reference.