analytics.js Youtube Plugin

With the analytics.js Youtube Plugin you can quickly get started collecting Youtube player events into the Segment ecosystem.

Prerequisites

Your Youtube player must be embedded via the Youtube IFrame player API, as the Segment Youtube Plugin requires the player JavaScript object as input.

Getting Started

1. Install

The plugin is distributed as both an NPM package and as a direct export via CDN.

CDN:

Simply add the following script tag to the head of your site, YoutubeAnalytics will then be available as part of the global window.analyticsPlugins object.

<script src="https://cdn.jsdelivr.net/npm/@segment/youtube-analytics@1.1.2/dist/youtube.js"></script>

NPM:

# latest stable
$ npm install @segment/youtube-analytics

2. Initialize

To initialize the plugin you will need to give it access to the Youtube video player instance(s) running on your page within the Youtube onYouTubeIframeAPIReady() function. This is done using the initialize method:

var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: 'M7lc1UVf-VE'
    });
    var ytAnalytics = new window.analyticsPlugins.YoutubeAnalytics(player)
    ytAnalytics.initialize()
}

That’s it! The plugin will now begin listening to the Youtube player for events and respond by firing the corresponding Segment Video Spec events on analytics.js.

Supported Events

The following Segment Video Spec events are tracked by this plugin:

  • Video Playback Started
    • If playing a single video, this will fire when the video starts
    • If playing a playlist, this will fire when the first video in the playlist starts
  • Video Playback Completed
    • If playing a single video, this will fire when the video finishes
    • If playing a playlist, this event will fire when the final video in the playlist finishes
  • Video Playback Paused/Resumed
  • Video Playback Buffer Started/Completed
  • Video Playback Seek Started/Completed
  • Video Content Started/Completed
    • For playlists, these events get fired for each individual video

Supported Properties

The following Segment Video Spec properties are automatically attached to the above events:

‘Playback’ Events

  • Total Length
  • Position
  • Quality
  • Video Player
  • Sound

‘Content’ Events

  • Title
  • Description
  • Keywords
  • Channel
  • Airdate
  • Duration

If you have any questions or see anywhere we can improve our documentation, please let us know or kick off a conversation in the Segment Community!