Skip to main content

YouTube media tracking on web

This plugin enables the automatic tracking of an embedded YouTube iFrame video, using the YouTube Player API.

It uses the Snowplow Media plugin under the hood.

YouTube media events and entities are automatically tracked once configured.

Install plugin

Tracker DistributionIncluded
sp.js
sp.lite.js

Download:

Download from GitHub Releases (Recommended)Github Releases (plugins.umd.zip)
Available on jsDelivrjsDelivr (latest)
Available on unpkgunpkg (latest)

Quick Start

The snippets below show how to get started with the plugin, after setting up your tracker.

Call startYouTubeTracking to begin tracking a YouTube video player, and endYouTubeTracking to stop tracking it.

html
<!DOCTYPE html>
<html>
<body>
<iframe
id="yt-player"
src="https://www.youtube.com/embed/zSM4ZyVe8xs"
></iframe>

<script>
window.snowplow(
'addPlugin',
'https://cdn.jsdelivr.net/npm/@snowplow/browser-plugin-youtube-tracking@latest/dist/index.umd.min.js',
['snowplowYouTubeTracking', 'YouTubeTrackingPlugin']
);

var mediaSessionId = crypto.randomUUID();

window.snowplow('startYouTubeTracking', {
id: mediaSessionId,
video: 'yt-player' // or: document.getElementById('yt-player')
});

window.snowplow('endYouTubeTracking', mediaSessionId);
</script>
</body>
</html>

Start tracking

The startYouTubeTracking function is used to begin auto-tracking a YouTube Player instance. You must provide a unique id for the media session, along with the video ID.

It installs the iFrame API if necessary, adds event listeners and any poll intervals, and then calls startMediaTracking from the underlying Snowplow Media plugin.

The function returns the mediaSessionId used for the events that will be generated.

ParameterTypeDescriptionDefault / Required
idstringA unique session UUID for each media element, used to identify and end tracking.Required
videoVideoLocationA DOM ID for the iFrame element hosting the player, an iFrame element, or a pre-existing YT.Player instance to track events for.Required
labelstringA custom human-readable label for the media element.undefined
captureEventsCapturableEvents[]A list of media events to track.All events tracked by default
boundariesnumber[]Percentage thresholds (0-100) to trigger progress events.[10, 25, 50, 75]
contextDynamicContextDynamic contexts attached to each tracking event.undefined
updatePageActivityWhilePlayingbooleanWhether to update page activity while media is playing.true
filterOutRepeatedEventsFilterOutRepeatedEventsWhether to suppress consecutive identical events.Enabled by default
filterOutRepeatedEvents .seekEventsbooleanWhether to filter out seek start and end events tracked after each other.true
filterOutRepeatedEvents .volumeChangeEventsbooleanWhether to filter out volume change events tracked after each other.true
filterOutRepeatedEvents .flushTimeoutMsnumberTimeout in milliseconds after which to send the events that are queued for filtering.5000 (milliseconds)
pings.pingIntervalnumberInterval (in seconds) for sending ping events.30 (seconds)
pings.maxPausedPingsnumberMaximum number of ping events sent while playback is paused.1
sessionboolean or objectWhether to track the media session entity for playback statistics, or set a custom start time.true

Stop tracking

The endYouTubeTracking function disables auto tracking for the player registered with the provided session ID.

It will remove any event listeners and poll intervals, and call endMediaTracking from the core plugin.

Events

Below is a table of all the core Snowplow Media plugin events that can be used in the captureEvents option:

NameFire condition
readyThe video player has loaded
playThe video is played
pauseThe video is paused
endWhen playback stops at the end of the video
seek_startWhen seeking begins to jump to another position of the video
seek_endWhen seeking ends and another position of the video is jumped to
playback_rate_changePlayback rate has changed
volume_changeVolume has changed
pingFires periodically during playback
percent_progressFires at progress milestones defined by boundaries option
buffer_startFires when playback pauses because content is not yet buffered
buffer_endFires when playback resumes after content has been fetched
quality_changePlayback quality has changed
errorAn error occurs in the player

In addition, the following event names are also accepted for compatibility with earlier tracker versions, mapped to the equivalent event from above:

NameFire condition
seekOn seek
volumechangeVolume has changed
endedWhen playback stops at the end of the video
percentprogressWhen a percentage boundary set in options.boundaries is reached
playbackratechangePlayback rate has changed
playbackqualitychangePlayback quality has changed

You can also use a pre-made event group names in captureEvents:

NameEvents
DefaultEvents['ready', 'play', 'pause', 'ping', 'end', 'seek_start', 'seek_end', 'volume_change', 'percent_progress', 'playback_rate_change', 'quality_change']
AllEventsEvery supported event in the Events table

It's possible to extend an event group with any event in the Events table above. This could be useful if you want, for example, all the events contained in the DefaultEvents group, along with the error event. This is expressed in the following way:

javascript
window.snowplow('startYouTubeTracking', {
id: crypto.randomUUID(),
video: "example-video",
captureEvents: ["DefaultEvents", "error"],
})

Unsupported events

The following events are defined by the core Snowplow Media plugin but aren't supported by the YouTube API, and so cannot be captured by this plugin:

NameFire condition
fullscreen_changeFull screen state toggled
picture_in_picture_changePicture-in-picture state toggled
ad_break_startBeginning of an ad break
ad_break_endEnd of an ad break
ad_startBeginning of an ad within an ad break
ad_first_quartile25% progress through an ad
ad_midpoint50% progress through an ad
ad_third_quartile75% progress through an ad
ad_complete100% progress through an ad
ad_skipUser has opted to skip the ad before completion
ad_clickUser has clicked the playing ad
ad_pauseUser has paused the playing ad
ad_resumeUser has resumed the paused ad

Add media entities to custom events

Use the trackYouTubeSelfDescribingEvent function to track custom event payloads that have the media-related entities attached as if they were generated by this or the core plugin directly.

html
<!DOCTYPE html>
<html>
<body>
<iframe
id="yt-player"
src="https://www.youtube.com/embed/zSM4ZyVe8xs"
></iframe>

<script>
window.snowplow(
'addPlugin',
'https://cdn.jsdelivr.net/npm/@snowplow/browser-plugin-youtube-tracking@latest/dist/index.umd.min.js',
['snowplowYouTubeTracking', 'YouTubeTrackingPlugin']
);

var mediaSessionId = crypto.randomUUID();

window.snowplow('startYouTubeTracking', {
id: mediaSessionId,
video: 'yt-player' // or: document.getElementById('yt-player')
});

window.snowplow('trackYouTubeSelfDescribingEvent', {event: {schema: 'iglu:com_example/my_event/jsonschema/1-0-0', data: { video: true }}});

window.snowplow('endYouTubeTracking', mediaSessionId);
</script>
</body>
</html>

YouTube player entity

The event and entity schemas are the same as for the Snowplow Media plugin.

Along with the standard Snowplow media entities, the YouTube media plugin also adds a youtube entity to all media events.

If you've configured the Media Player dbt package to use the v1 schemas, or are using an older version of the Media Player model, it will use fields from the youtube entity. The Media Player model version 0.6+ doesn't use this entity.

youtube

Entity
Context Schema for a youtube player event
Schema URIiglu:com.youtube/youtube/jsonschema/1-0-0
Example
json
{
"autoPlay": false,
"avaliablePlaybackRates": [
0.25,
0.5,
0.75,
1,
1.25,
1.5,
1.75,
2
],
"buffering": false,
"controls": true,
"cued": false,
"loaded": 17,
"playbackQuality": "hd1080",
"playerId": "example-id",
"unstarted": false,
"url": "https://www.youtube.com/watch?v=zSM4ZyVe8xs",
"yaw": 0,
"pitch": 0,
"roll": 0,
"fov": 100.00004285756798,
"avaliableQualityLevels": [
"hd2160",
"hd1440",
"hd1080",
"hd720",
"large",
"medium",
"small",
"tiny",
"auto"
]
}
Properties and schema
PropertyDescription
avaliablePlaybackRates
array
Required. An array of playback rates in which the current video is available
avaliableQualityLevels
array
Optional. An array of quality levels in which the current video is available
cued
boolean
Required. If the video is cued
playerId
string
Required. The HTML id of the video element
autoPlay
boolean
Required. This specifies whether the initial video will automatically start to play when the player loads.
buffering
boolean
Required. If the player is buffering
controls
boolean
Required. Whether the video player controls are displayed
error
string
Optional. A string of the latest error to occur, or null if no errors
Must be one of: INVALID_PARAMETER, HTML5_PLAYER_ERROR, NOT_FOUND, EMBED_DISALLOWED
loaded
integer
Required. The percentage of the video that the player shows as buffered
origin
string
Optional. The origin domain of the embed
playbackQuality
string
Required. The quality level of the current video
playlist
array
Optional. An array of the video IDs in the playlist as they are currently ordered.
playlistIndex
number
Optional. The index of the playlist video that is currently playing
unstarted
boolean
Required. If the player hasn't started
url
string
Required. The YouTube embed URL of the media resource
fov
number
Optional. The field-of-view of the view in degrees, as measured along the longer edge of the viewport
roll
number
Optional. The clockwise or counterclockwise rotational angle of the view in degrees
pitch
number
Optional. The vertical angle of the view in degrees
yaw
number
Optional. The horizontal angle of the view in degrees

Legacy API

In addition to the above, the following methods are provided for compatibility with earlier versions of the plugin.

These APIs are deprecated in tracker version 4, and wrap the newer API methods above.

Enable tracking

The enableYouTubeTracking function is similar to startYouTubeTracking, except:

  • An id option is used to identify the player instead of video
  • The additional options to startMediaTracking are nested within an options object
  • The media session ID value will be generated automatically if not provided
info
The plugin's id option is equivalent to video in the new API and will accept:
  • The id of an iframe element
  • An iframe element directly
  • An existing instance of YT.Player, created with the YouTube Iframe API

The enableYouTubeTracking function takes the form:

javascript
window.snowplow("enableYouTubeTracking", { id, options?: { label?, captureEvents?, boundaries?, updateRate? } })
ParameterTypeDefaultDescriptionRequired
idstring or YT.Player-The HTML id attribute of the media elementYes
options.labelstring-An identifiable custom label sent with the eventNo
options.captureEventsstring[]['DefaultEvents']The events or Event Group to capture. For a full list of events and groups, check the section belowNo
options.boundariesnumber[][10, 25, 50, 75]The progress percentages to fire an event at (valid values 1 - 99 inclusive)No
options.*anyAny other options are passed through to startMediaTrackingNo

Below is an example of the full enableYouTubeTracking function:

javascript
window.snowplow('enableYouTubeTracking', {
id: 'example-video',
options: {
label: 'My Custom Video Label',
captureEvents: ['play', 'pause', 'ended'],
boundaries: [20, 80],
updateRate: 500,
}
})

Disable tracking

The disableYouTubeTracking function is an equivalent counterpart to endYouTubeTracking for enableYouTubeTracking.

Instead of requiring the session ID to be provided, it will remove the oldest of any sessions started with enableYouTubeTracking so the session ID doesn't need to be known and passed explicitly.