# HTML5 media tracking on web
> Automatically track HTML5 video and audio elements with media events including play, pause, seek, buffer, and progress milestones.
> Source: https://docs.snowplow.io/docs/sources/web-trackers/tracking-events/media/html5/
> Documentation index: https://docs.snowplow.io/llms.txt

This plugin enables the automatic tracking of HTML5 media elements (`<video>` and `<audio>`) on a webpage.

It uses the [Snowplow Media plugin](/docs/sources/web-trackers/tracking-events/media/snowplow/) under the hood.

HTML5 media events and entities are **automatically tracked** once configured.

## Install plugin

**JavaScript (tag):**

| Tracker Distribution | Included |
| -------------------- | -------- |
| `sp.js`              | ❌        |
| `sp.lite.js`         | ❌        |

**Download:**

|                                             |                                                                                                               |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Download from GitHub Releases (Recommended) | [Github Releases (plugins.umd.zip)](https://github.com/snowplow/snowplow-javascript-tracker/releases)         |
| Available on jsDelivr                       | [jsDelivr](https://cdn.jsdelivr.net/npm/@snowplow/browser-plugin-media-tracking@4.10.2/dist/index.umd.min.js) |
| Available on unpkg                          | [unpkg](https://unpkg.com/@snowplow/browser-plugin-media-tracking@4.10.2/dist/index.umd.min.js)               |

**Note:** The links to the CDNs above are pinned to a specific version at the time of writing. Check the [plugin's GitHub releases](https://github.com/snowplow/snowplow-javascript-tracker/releases) for newer versions, and update the pinned version when you upgrade.

```javascript
window.snowplow('addPlugin',
  "https://cdn.jsdelivr.net/npm/@snowplow/browser-plugin-media-tracking@4.10.2/dist/index.umd.min.js",
  ["snowplowMediaTracking", "MediaTrackingPlugin"]
);
```

**Browser (npm):**

- `npm install @snowplow/browser-plugin-media-tracking`
- `yarn add @snowplow/browser-plugin-media-tracking`
- `pnpm add @snowplow/browser-plugin-media-tracking`

```javascript
import { newTracker, trackPageView } from '@snowplow/browser-tracker';
import { MediaTrackingPlugin, startHtml5MediaTracking } from '@snowplow/browser-plugin-media-tracking';

newTracker('sp1', '{{collector_url}}', {
   appId: 'my-app-id',
   plugins: [ MediaTrackingPlugin() ],
});

startHtml5MediaTracking(/* options */);
```

***

## Quick Start

To start tracking media with default settings:

**JavaScript (tag):**

**`main.js`**

```html
<video id='html-id' src='./video.mp4'></video>
<script>
  window.snowplow('addPlugin',
    "https://cdn.jsdelivr.net/npm/@snowplow/browser-plugin-media-tracking@4.10.2/dist/index.umd.min.js",
    ["snowplowMediaTracking", "MediaTrackingPlugin"]
  );

  const sessionId = crypto.randomUUID();

  window.snowplow('startHtml5MediaTracking', {
    id: sessionId,
    video: 'html-id',
  })
</script>
```

**`index.html`**

```html
<video id='html-id' src='./video.mp4'></video>
```

**Browser (npm):**

**`main.js`**

```javascript
import { startHtml5MediaTracking } from '@snowplow/browser-plugin-media-tracking'

const sessionId = crypto.randomUUID();

startHtml5MediaTracking({
  id: sessionId,
  video: 'html-id',
})
```

**`index.html`**

```html
<video id='html-id' src='./video.mp4'></video>
```

***

## Start tracking

Start tracking HTML5 media by calling the `startHtml5MediaTracking` function with a configuration object. You must provide a unique `id` for the media session, along with the `video` ID.

**JavaScript (tag):**

```javascript
window.snowplow('startHtml5MediaTracking', {
  id: "unique-session-id",
  video: "myVideoElement",
  label: "Product Demo Video",
  captureEvents: ["play", "pause", "end"],
  boundaries: [25, 50, 75, 100],
  pings: {
    pingInterval: 20,
    maxPausedPings: 2,
  },
  updatePageActivityWhilePlaying: true,
  filterOutRepeatedEvents: {
    seekEvents: true,
    volumeChangeEvents: false,
    flushTimeoutMs: 5000
  },
  session: {
    // Custom session start time
    startedAt: new Date('2024-01-01T12:00:00Z'),
  },
});
```

**Browser (npm):**

```javascript
startHtml5MediaTracking({
  id: "unique-session-id",
  video: document.getElementById("myVideoElement"),
  label: "Product Demo Video",
  captureEvents: ["play", "pause", "end"],
  boundaries: [25, 50, 75, 100],
  pings: {
    pingInterval: 20,
    maxPausedPings: 2,
  },
  updatePageActivityWhilePlaying: true,
  filterOutRepeatedEvents: {
    seekEvents: true,
    volumeChangeEvents: false,
    flushTimeoutMs: 5000
  },
  session: {
    // Custom session start time
    startedAt: new Date('2024-01-01T12:00:00Z'),
  },
});
```

***

| Parameter                                       | Type                                                                                                                 | Description                                                                                    | Default / Required            |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------- |
| `id`                                            | `string`                                                                                                             | A unique session UUID for each media element, used to identify and end tracking.               | Required                      |
| `video`                                         | `string` or `HTMLMediaElement`                                                                                       | The ID of the media element (as a string) or the media element itself.                         | Required                      |
| `label`                                         | `string`                                                                                                             | A human-readable label for the media element.                                                  | `undefined`                   |
| `captureEvents`                                 | `HTML5MediaEventTypes`                                                                                               | A list of media events to track.                                                               | All events tracked by default |
| `boundaries`                                    | `number[]`                                                                                                           | Percentage thresholds (0-100) to trigger progress events.                                      | `[10, 25, 50, 75]`            |
| `context`                                       | [`DynamicContext`](/docs/sources/web-trackers/custom-tracking-using-schemas/global-context/#global-contexts-methods) | Dynamic contexts attached to each tracking event.                                              | `undefined`                   |
| `updatePageActivityWhilePlaying`                | `boolean`                                                                                                            | Whether to update page activity while media is playing.                                        | `true`                        |
| `filterOutRepeatedEvents`                       | `FilterOutRepeatedEvents`                                                                                            | Whether to suppress consecutive identical events.                                              | Enabled by default            |
| `filterOutRepeatedEvents` `.seekEvents`         | `boolean`                                                                                                            | Whether to filter out seek start and end events tracked after each other.                      | `true`                        |
| `filterOutRepeatedEvents` `.volumeChangeEvents` | `boolean`                                                                                                            | Whether to filter out volume change events tracked after each other.                           | `true`                        |
| `filterOutRepeatedEvents` `.flushTimeoutMs`     | `number`                                                                                                             | Timeout in milliseconds after which to send the events that are queued for filtering.          | `5000` (milliseconds)         |
| `pings.pingInterval`                            | `number`                                                                                                             | Interval (in seconds) for sending ping events.                                                 | `30` (seconds)                |
| `pings.maxPausedPings`                          | `number`                                                                                                             | Maximum number of ping events sent while playback is paused.                                   | `1`                           |
| `session`                                       | `boolean` or `object`                                                                                                | Whether to track the media session entity for playback statistics, or set a custom start time. | `true`                        |

## Stop tracking

End tracking by calling `endHtml5MediaTracking`. This 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`](/docs/sources/web-trackers/tracking-events/media/snowplow/#usage) from the core plugin.

**JavaScript (tag):**

**`main.js`**

```html
<video id='html-id' src='./video.mp4'></video>
<script>
  window.snowplow('addPlugin',
    "https://cdn.jsdelivr.net/npm/@snowplow/browser-plugin-media-tracking@4.10.2/dist/index.umd.min.js",
    ["snowplowMediaTracking", "MediaTrackingPlugin"]
  );

  const sessionId = crypto.randomUUID();

  window.snowplow('startHtml5MediaTracking', {
    id: sessionId,
    video: 'html-id',
  })

  // Tracking some video events...

  window.snowplow('endHtml5MediaTracking', sessionId)
</script>
```

**Browser (npm):**

**`main.js`**

```javascript
import { startHtml5MediaTracking, endHtml5MediaTracking } from '@snowplow/browser-plugin-media-tracking'

const sessionId = crypto.randomUUID();

startHtml5MediaTracking({
  id: "session-id",
  video: 'html-id',
})

// Tracking some video events...

endHtml5MediaTracking(sessionId)
```

**`index.html`**

```html
<video id='html-id' src='./video.mp4'></video>
```

***

## Events

The HTML5 media plugin can track the following events:

| Event Type             | Event String                | Description                                                                                   |
| ---------------------- | --------------------------- | --------------------------------------------------------------------------------------------- |
| Ready                  | `ready`                     | Fired when media tracking is successfully attached to the player and ready to track events.   |
| Play                   | `play`                      | Fired when the player transitions from a paused state to playing.                             |
| Pause                  | `pause`                     | Fired when the user pauses the playback.                                                      |
| End                    | `end`                       | Fired when playback stops because the media has reached its end or no more data is available. |
| SeekEnd                | `seek_end`                  | Fired when a seek operation is completed.                                                     |
| PlaybackRateChange     | `playback_rate_change`      | Fired when the playback rate (speed) of the media changes.                                    |
| VolumeChange           | `volume_change`             | Fired when the volume level of the media changes.                                             |
| FullscreenChange       | `fullscreen_change`         | Fired when the browser enters or exits full-screen mode.                                      |
| PictureInPictureChange | `picture_in_picture_change` | Fired when the browser enters or exits picture-in-picture mode.                               |
| BufferStart            | `buffer_start`              | Fired when the media player starts buffering (loading content to play).                       |
| BufferEnd              | `buffer_end`                | Fired when buffering ends, and playback resumes.                                              |
| Error                  | `error`                     | Fired when an error occurs during the loading or playback of the media.                       |
| Ping                   | `ping`                      | Fired periodically during media playback, regardless of other events.                         |
| PercentProgress        | `percent_progress`          | Fired when a specific percentage of the media content has been played (as set by boundaries). |

It's possible to only track a subset of these events by passing an array of event types to the `captureEvents` option:

**JavaScript (tag):**

```javascript
window.snowplow("startHtml5MediaTracking", {
  id: crypto.randomUUID(),
  video: 'example-video',
  captureEvents: ['play', 'pause'],
})
```

**Browser (npm):**

```javascript
import { startHtml5MediaTracking, HTML5MediaEventTypes } from '@snowplow/browser-plugin-media-tracking'

const sessionId = uuidv4();

startHtml5MediaTracking({
  id: crypto.randomUUID(),
  video: 'example-video',
  captureEvents: [HTML5MediaEventTypes.Play, HTML5MediaEventTypes.Pause],
})
```

***

## Additional entities

The event and entity schemas are [the same as](/docs/events/ootb-data/media-events/) for the [Snowplow Media plugin](/docs/sources/web-trackers/tracking-events/media/snowplow/).

Along with the standard Snowplow media entities, the HTML5 media plugin also tracks two HTML5 media-specific entities, `media_element` and `video_element`.

For `<video>` elements, both entities are added to all media events in the session. For `<audio>` elements, only the `media_element` entity is added.

If you've configured the [Media Player](/docs/modeling-your-data/modeling-your-data-with-dbt/dbt-models/dbt-media-player-data-model/) dbt package to use the [v1 schemas](/docs/events/ootb-data/media-events/#media-api-versions), or are using an older version of the Media Player model, it will use fields from the `media_element` and `video_element` entities. The Media Player model version 0.6+ doesn't use them.

### HTML5 media element

### `media_element`

**Type:** Schema

Context Schema for a media player event

**Properties:**

| Property                          | Description                                                                                                                                                     |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `autoPlay` _boolean_              | _Required._ If playback should automatically begin as soon as enough media is available to do so without interruption                                           |
| `buffered` _array_                | _Required._ An array of time ranges that have been buffered                                                                                                     |
| `controls` _boolean_              | _Required._ If the user agent should provide it's own set of controls                                                                                           |
| `crossOrigin` _string_            | _Optional._ CORS settings value of the media player                                                                                                             |
| `currentSrc` _string_             | _Required._ The absolute URL of the media resource                                                                                                              |
| `defaultMuted` _boolean_          | _Required._ If audio is muted by default                                                                                                                        |
| `defaultPlaybackRate` _number_    | _Required._ The default media playback rate of the player                                                                                                       |
| `disableRemotePlayback` _boolean_ | _Optional._ If the media element is allowed to have a remote playback UI                                                                                        |
| `error` _object_                  | _Required._ An object of the latest error to occur, or null if no errors                                                                                        |
| `fileExtension` _string_          | _Optional._ The media file format                                                                                                                               |
| `fullscreen` _boolean_            | _Optional._ If the video element is fullscreen                                                                                                                  |
| `mediaType` _string_              | _Required._ If the media is a video element, or audio Must be one of: `AUDIO`, `VIDEO`                                                                          |
| `networkState` _string_           | _Required._ The current state of the fetching of media over the network Must be one of: `NETWORK_EMPTY`, `NETWORK_IDLE`, `NETWORK_LOADING`, `NETWORK_NO_SOURCE` |
| `pictureInPicture` _boolean_      | _Optional._ If the video element is showing Picture-In-Picture                                                                                                  |
| `played` _array_                  | _Optional._ An array of time ranges played                                                                                                                      |
| `htmlId` _string_                 | _Required._ The HTML id of the element                                                                                                                          |
| `preload` _string_                | _Required._ The 'preload' HTML attribute of the media                                                                                                           |
| `readyState` _string_             | _Required._ The readiness of the media Must be one of: `HAVE_NOTHING`, `HAVE_METADATA`, `HAVE_CURRENT_DATA`, `HAVE_FUTURE_DATA`, `HAVE_ENOUGH_DATA`             |
| `seekable` _array_                | _Required._ Seekable time range(s)                                                                                                                              |
| `seeking` _boolean_               | _Required._ If the media is in the process of seeking to a new position                                                                                         |
| `src` _string_                    | _Optional._ The 'src' HTML attribute of the media element                                                                                                       |
| `textTracks` _array_              | _Optional._ An array of TextTrack objects on the media element                                                                                                  |

### HTML5 video element

### `video_element`

**Type:** Schema

Context Schema for a video player event

**Properties:**

| Property                            | Description                                                                                                                                             |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `autoPictureInPicture` _boolean_    | _Optional._ A boolean value that is true if the video should enter or leave picture-in-picture mode automatically when changing tab and/or application  |
| `disablePictureInPicture` _boolean_ | _Optional._ The disablePictureInPicture property will hint the user agent to not suggest the picture-in-picture to users or to request it automatically |
| `poster` _string_                   | _Optional._ 'poster' HTML attribute, which specifies an image to show while no video data is available                                                  |
| `videoHeight` _integer_             | _Required._ A value indicating the intrinsic height of the resource in CSS pixels, or 0 if no media is available yet                                    |
| `videoWidth` _integer_              | _Required._ A value indicating the intrinsic width of the resource in CSS pixels, or 0 if no media is available yet                                     |
