Program Guide Analytics
Integrating the analytics module in to the Program Guide app
Let's continue with the Program Guide, a full-featured app that lets the viewer choose and play a selection of videos. You'll see how the analytics module fits in perfectly and lets you log all the videos the viewer watches with minimal additional code.
- Repo: https://github.com/synamedia-senza/program-guide/
- Pull request: https://github.com/synamedia-senza/program-guide/pull/2/files
Clone the repo and switch to the analytics branch to follow along. As usual, the pull request shows what changes we've made to the app.
Setup
We'll put most of the code in the PlayerWidget class in the /src/widgets/player.js file. We'll create a method called initAnalytics(), and call it from the constructor.
constructor() {
...
this.initAnalytics();
}
async initAnalytics() {
const config = await this.loadAnalyticsConfig();
await analytics.init("Program Guide", {
google: {gtag: config.googleAnalyticsId, debug: true},
ipdata: {apikey: config.ipDataAPIKey},
lifecycle: {raw: false, summary: true},
player: {raw: false, summary: true}
});
analytics.trackPlayerEvents(this.player, this.video, (ctx) => this.asset);
}
async loadAnalyticsConfig(url = "./src/config.json") {
try {
const res = await fetch(url, { cache: "no-store" });
if (!res.ok) return {};
return await res.json();
} catch {
console.warn("Analytics config.json not found");
return {};
}
}
This example shows how to load the config.json file using the fetch() function.
Tracking player events
In the code above, you'll notice this line that we use for tracking player events. This object already has properties storing the player, video and the current asset.
analytics.trackPlayerEvents(this.player, this.video, (ctx) => this.asset);
The analytics module will automatically track viewing activity like this:
- When the user selects a video, the app loads it by calling
player.load(). This triggers aplayer_session_startevent. - When they return to the home page, the app unloads the video by calling
player.unload(). This triggers aplayer_session_endevent.
Note that we pass an arrow function that points to this.asset. That function will be called whenever a new video is loaded, so every viewing session will be created with the metadata for the current asset, including the title, description, etc.
Testing
In this example, we started watching Elephant’s Dream, went back to the home page, selected Sintel, and then disconnected. You'll see the player session start and end events in the Remote Debugger console.

Notice how the content metadata is included in both of these events. If we turned on raw player events, it would not be included in these to limit the amount of data sent.
In the GA4 debug view, you can see how the player session start and end events are bracketed. The timeline shows how they are sent at the beginning and end of each viewing session.

Updated 3 days ago