UNPKG

@dailymotion/ad-sdk-web

Version:
315 lines (218 loc) β€’ 15.7 kB
# Ad SDK Web A lightweight web wrapper for Dailymotion's Ad SDK – load, manage, and interact with video ads easily in modern web players. [![npm](https://img.shields.io/npm/v/@dailymotion/ad-sdk-web.svg)](https://www.npmjs.com/package/@dailymotion/ad-sdk-web) ## βš™οΈ Required HTML & CSS Setup for the Player Container To use our Ad SDK Web, you must define an HTML player container element styled correctly to hold both your content video tag and Ad SDK playback elements. ### CSS styles to add ``` .videoPlayerContainer { position: relative; width: auto; height: 100%; aspect-ratio: 16 / 9; } ``` `.videoPlayerContainer` is the wrapper where the SDK mounts the ad container and your video element. The container is positioned relative to allow absolute positioning of ad overlays if needed. The aspect ratio keeps the player consistent across screen sizes. ## Example implementation reference πŸ‘‰ Check out an example implementation here: https://dailymotion.github.io/ad-sdk-sample/ ## πŸ“˜ Public API Documentation ### `async initialize(playerContainer: HTMLElement): Promise<void>` Loads the external ad SDK script and creates internal DOM elements for ad playback.<br /> This method should be called before any other function of the SDK and once per page. **Parameters:** - `playerContainer`: `HTMLElement` The DOM element where the ad container will be mounted. **Throws:** If the container is missing or the script fails to load. --- ### `loadAdsSequence(appState: AppState, developmentOptions?: DevelopmentOptions): Promise<void>` Loads ads sequence with the provided contextual information. <br /> After this call, the ad SDK will listen to the progress of the video and will trigger an `AD_BREAK_START` event whenever an ad break is about to begin. When this event occurs, the video player is expected to pause playback. Playback should resume only after the corresponding AD_BREAK_END event is received. <br /> A preroll ad may start automatically after this call. If no preroll is available, the SDK will send an AD_BREAK_END event to indicate that content playback can proceed.<br /> This method should be called once per video, before starting the main content. **Parameters:** - `appState`: `AppState` A structured object providing ad targeting and playback environment data. πŸ‘‰ **See full structure below** or jump to [AppState](#AppState) - `developmentOptions`: `DevelopmentOptions` Optional settings used only during development. πŸ‘‰ **See full structure below** or jump to [DevelopmentOptions](#DevelopmentOptions) --- ### `playAd(): void` Request the SDK to start the ad playback. **Throws:** If the SDK is not initialized. --- ### `pauseAd(): void` Request the SDK to pause the ad. **Throws:** If the SDK is not initialized. --- ### `skipAd(): void` Request the SDK to skip the currently playing ad. **Throws:** If the SDK is not initialized. --- ### `getAdDetails(): AdDetails` Returns detailed information about the currently playing ad. **Returns:** An `AdDetails` object containing properties such as `position`, ad duration, and other metadata. πŸ‘‰ **See full structure below** or jump to [AdDetails](#AdDetails) --- ### `on(event: AdEvents, callback: EventCallback): void` Subscribes to a specific Ad SDK event. **Parameters:** - `event`: `AdEvents` The event name to listen for. πŸ‘‰ **See [`AdEvents`](#AdEvents) for available event names.** - `callback`: `EventCallback` The callback function to execute when the event occurs. **Callback signature depends on the event:** - For `AD_ERROR`: `(code?: number, message?: string) => void` The callback receives optional VAST error code and message parameters. - For all other events: `() => void` The callback receives no parameters. **Throws:** If the Ad SDK is not initialized. **Example:** ```typescript // Standard event callback (no parameters) adSDK.on(adSDK.Events.AD_BREAK_START, () => { console.log('Ad break started') }) // Error event callback (with code and message) adSDK.on(adSDK.Events.AD_ERROR, (code, message) => { console.error('Ad error:', code, message) }) ``` --- ### `off(event: AdEvents, callback: EventCallback): void` Unsubscribes from a specific Ad SDK event. **Parameters:** - `event`: `AdEvents` The event name to stop listening for. πŸ‘‰ **See [`AdEvents`](#AdEvents) for available event names.** - `callback`: `EventCallback` The callback function to remove. Must be the same function reference that was passed to `on()`. **Callback signature depends on the event:** - For `AD_ERROR`: `(code?: number, message?: string) => void` - For all other events: `() => void` **Throws:** If the Ad SDK is not initialized. --- ### `updateAppState(appState: AppState): void` Updates the SDK with a new state payload. **Parameters:** - `appState`: `AppState` Updated app context data. πŸ‘‰ **See full structure below** or jump to [AppState](#AppState) --- <br /> # Data structures ## AppState | Parameter | Type | Required | Description | | ----------- | ------------------ | -------- | --------------------------------------------------------------------------------------- | | consent | Consent | yes | User consent and privacy settings relevant for ad personalization and legal compliance. | | video | VideoState | yes | Current video playback state and characteristics affecting ad behavior. | | environment | EnvironmentContext | yes | Context about the app environment, locale, and device details. | | player | PlayerContext | yes | Settings and references related to the video player instance. | ## Consent | Parameter | Type | Required | Default | Description | | ------------------------------- | -------- | -------- | -------- | ------------------------------------------------------------------------------ | | ccpaConsent | string | no | `'1---'` | User’s consent status under the California Consumer Privacy Act. | | tcfConsent | string | no | `''` | Consent string according to the IAB Transparency and Consent Framework (TCF). | | tcf2HasConsentForGoogle | boolean | no | `false` | Whether consent has been given for Google in TCF v2 context. | | tcf2HasConsentForDailymotion | boolean | no | `false` | Whether consent has been given for Dailymotion in TCF v2 context. | | isGdprApplicable | boolean | no | `false` | Indicates if GDPR regulations apply to the current user/session. | | gppConsentStringFromPlayer | string | no | `''` | GPP consent string received from the player. | | gppApplicableSectionsFromPlayer | number[] | no | `[]` | Array of GPP section IDs that apply to the user based on player configuration. | ## VideoState | Parameter | Type | Required | Default | Description | | ------------------ | ------- | -------- | ------- | ---------------------------------------------------------------- | | id | string | yes | β€” | The video id | | isAutoplay | boolean | yes | β€” | Whether the video is set to autoplay. | | type | string | yes | β€” | Indicates if the type of the video. `LIVE` \| `STREAM` | | isCurrentTimeDVR | boolean | yes | β€” | Whether the current playback position is within a DVR window. | | isSeekable | boolean | yes | β€” | Whether the video player supports seeking functionality. | | duration | number | no | `0` | The duration of the video | | viewId | string | yes | β€” | Unique identifier for the video view or playback session. | | publisherId | string | yes | β€” | Identifier of the content publisher. | | publisherType | string | yes | β€” | Type/category of the publisher. | | publisherReference | string | yes | β€” | Reference code or identifier of the publisher. | | playlistId | string | no | `''` | The playlist id. | | streamTech | string | no | `''` | Playback technology used by the stream. `'hls.js'` \| `'native'` | | ownerId | string | no | `''` | Identifier of the video owner account. | | ownerParentId | string | no | `''` | Identifier of the owner's parent. | | protectedDelivery | boolean | no | β€” | | | createdTime | number | no | `0` | Video creation timestamp in milliseconds since epoch. | | isPasswordProtected| boolean | no | false | Whether the video requires a password to view. | | isPrivate | boolean | no | false | Whether the video is private. | | mimeType | string | yes | β€” | MIME type of the content, e.g., `video/mp4`. | ## EnvironmentContext | Parameter | Type | Required | Description | | -------------------------- | ------- | -------- | ----------------------------------------------------------------- | | appName | string | yes | Name of the app or website embedding the player. | | locale | string | yes | Locale or language setting for the user session. | | topDomain | string | yes | The top-level domain of the page embedding the player. | | embedder | string | yes | Identifier or name of the embedding entity or partner. | | clientType | string | yes | Type of client (e.g., web, mobile app, CTV). | | deviceId | string | yes | Unique identifier for the user’s device. | | trafficSegment | number | yes | Numeric segment ID used for traffic or user segmentation. | | v1st | string | yes | A unique ID automatically assigned to your device by Dailymotion. | | is3rdPartyCookiesAvailable | boolean | yes | Indicates if third-party cookies are accessible in this context. | | osFamily | string | no | Operating system family parsed from UA, e.g., `Linux`. | | osName | string | no | Operating system name parsed from UA, e.g., `Ubuntu`. | | uaFamily | string | no | User agent family, e.g., `Chromium`. | | uaName | string | no | User agent name, e.g., `Chrome`. | | uaVersion | string | no | User agent version, e.g., `120.0.0`. | ## PlayerContext | Parameter | Type | Required | Description | | ----------------------- | ---------------- | -------- | ---------------------------------------- | | videoTag | HTMLVideoElement | yes | Reference to the HTML video element. | | isPlayerControlsEnabled | boolean | yes | Whether the player controls are enabled. | ## DevelopmentOptions Intended **only for development and testing purposes.** | Parameter | Type | Required | Description | | --------- | ------- | -------- | ----------------------------- | | useFakeAd | boolean | no | Enables a fake ad simulation. | <br /> # Internal data models ## AdDetails | Parameter | Type | Description | | ----------------- | ------------------------------------ | ------------------------------------------------------------ | | skipOffset | number | Time in seconds after which the ad can be skipped. | | duration | number | Total duration of the ad in seconds. | | mediaFile | string | URL of the media file (video/audio) for the ad. | | impressionTracker | string | URL used to track ad impressions (views). | | midrollTime | number | Timestamp in the main content when a midroll ad should play. | | position | 'preroll' \| 'midroll' \| 'postroll' | Indicates the ad position relative to the main content. | ## AdEvents | Parameter | Description | Callback Signature | | ------------------------ | -------------------------------------------------- | ------------------------------------- | | AD_BREAK_START | Sent when the ad break has started | `() => void` | | AD_BREAK_END | Sent when the ad break has ended | `() => void` | | AD_LOAD | Sent when the ad has loaded | `() => void` | | CONTENT_PAUSE_REQUESTED | Sent to pause the content for midroll ads | `() => void` | | AD_START | Sent when the ad has started | `() => void` | | AD_PLAY | Sent when the ad is played | `() => void` | | AD_PAUSE | Sent when the ad is paused | `() => void` | | AD_END | Sent when an ad has ended | `() => void` | | AD_ERROR | Sent when an error preventing to play an ad occurs | `(code?: number, message?: string) => void` | | CONTENT_RESUME_REQUESTED | Sent to resume content after an ad | `() => void` | **Note:** The `AD_ERROR` event callback receives optional `code` (number) and `message` (string) parameters containing VAST error information. The error code corresponds to IAB VAST error codes (e.g., 100, 300, 400, etc.). All other events use a callback with no parameters. <br /> # SDK and Events sequences for each ad position ## Preroll sequence <img src="https://statics.dmcdn.net/h/ad-sdk-web/preroll_sequence.png?v1" alt="Preroll sequence" width="500"/> ## Midroll sequence <img src="https://statics.dmcdn.net/h/ad-sdk-web/midroll_sequence.png?v1" alt="Midroll sequence" width="500"/> ## Postroll sequence <img src="https://statics.dmcdn.net/h/ad-sdk-web/postroll_sequence.png?v1" alt="Postroll sequence" width="500"/>