Integrating advertisements into JavaScript video players involves using standardized protocols to deliver video ads during playback. VAST (Video Ad Serving Template) and IMA (Interactive Media Ads) define formats and methods for requesting, displaying, and tracking video advertisements.

These protocols support inserting ads at specific points, such as before, during, or after the main video content, and provide a consistent way to handle ad playback and reporting across different players and platforms.

Understanding VAST and IMA

VAST (Video Ad Serving Template) is a standard developed by the Interactive Advertising Bureau (IAB) to serve ads in video players. It allows for the delivery of video ads in a structured format, supporting features like skippable ads, companion ads, and ad tracking. VAST is commonly used in video players for pre-roll, mid-roll, and post-roll ads.

IMA (Interactive Media Ads) is a set of APIs developed by Google to integrate video ads into video content. It extends the functionality of VAST by providing features like ad events, interactive features (e.g., overlays and buttons), and enhanced tracking. IMA is most often used with Google's IMA SDK, which simplifies the integration process for developers.

Setting Up VAST Ads in JS Video Players

To integrate VAST ads into a video player, you typically need to fetch the VAST XML response from an ad server and load it into the player using JavaScript. Here's a step-by-step guide for integrating VAST ads into a standard HTML5 video player.

Step 1: Install a VAST-compatible JS Ad Plugin

You can use libraries like videojs-vast-plugin to make the integration process easier. First, include the required libraries in your HTML file:

code
<!-- Video.js CSS and JS -->
<link href="https://vjs.zencdn.net/8.10.0/video-js.css" rel="stylesheet" />
<script src="https://vjs.zencdn.net/8.10.0/video.min.js"></script>

<!-- Video.js contrib-ads and IMA plugin (for VAST support) -->
<script src="https://cdn.jsdelivr.net/npm/videojs-contrib-ads@6.9.0/dist/videojs-contrib-ads.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/videojs-ima@1.10.0/dist/videojs.ima.min.js"></script>

Step 2: Configure the Video Player with VAST

Set up your HTML video element and initialize Video.js with the IMA plugin, providing the ad server URL for fetching ads.

code
<video
id="my-video"
class="video-js vjs-default-skin"
controls
width="640"
height="360"
poster="poster.jpg"
>
<source src="your-video.mp4" type="video/mp4" />
</video>

Explanation:

  • The url parameter points to the VAST ad server URL, where the ad details are fetched.
  • adsEnabled: true enables ad functionality within the player.
  • adPod: false indicates that the player should not handle pod ads (sequential ads) but will request individual ads.

Step 3: Initialize Video.js and Configure VAST/IMA

Initialize the player instance, configure the IMA plugin with the VAST ad tag URL, and set up event listeners for ad lifecycle events.

code
<script>
var player = videojs('my-video');

player.ima({
adTagUrl: 'https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dlinear&correlator=',
debug: true
});

player.on('play', function() {
player.ima.initializeAdDisplayContainer();
});

// Optional: handle ad events
player.on('ads-ad-started', function() {
console.log('Ad started');
});
player.on('ads-ad-ended', function() {
console.log('Ad ended');
});
player.on('adserror', function(e) {
console.error('Ad error:', e);
});
</script>
Banner for VAST Ads

Handling VAST Ad Events

When integrating VAST ads, it's essential to track ad events like adStart, adError, and adComplete to manage ad playback effectively and provide feedback.

code
player.on('adstart', function() {
console.log('Ad started');
});

player.on('aderror', function(e) {
console.error('Ad error: ', e);
});

player.on('adcomplete', function() {
console.log('Ad completed');
});

Explanation:

  • adstart: Triggered when the ad starts playing.
  • aderror: Triggered when there is an error with the ad (e.g., loading error).
  • adcomplete: Triggered when the ad finishes playing.

These events allow developers to track and respond to ad playback, such as showing user notifications or handling ad retries.

Integrating IMA Ads with Google IMA SDK

Google's Interactive Media Ads (IMA) SDK provides a more advanced way of integrating ads, offering more flexibility for interactive video ads. It includes rich tracking, real-time reporting, and advanced ad formats.

Step 1: Install the IMA SDK

To use IMA with a JS video player, include the IMA SDK in your HTML file:

code
<script src="https://imasdk.googleapis.com/js/sdkloader/ima3.js"></script>

Step 2: Setup IMA in the Video Player

To integrate IMA with your video player, initialize the SDK and request an ad tag from the ad server:

code
<video id="content_video" width="640" height="360" controls poster="poster.jpg">
<source src="your-video.mp4" type="video/mp4" />
</video>
<div id="adContainer" style="position:absolute; top:0; left:0; width:640px; height:360px; z-index:1000;"></div>


<script>
var videoContent = document.getElementById('content_video');
var adContainer = document.getElementById('adContainer');

var adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoContent);

function initAdDisplayContainer() {
adDisplayContainer.initialize();
videoContent.removeEventListener('click', initAdDisplayContainer);
}
videoContent.addEventListener('click', initAdDisplayContainer);

var adsLoader = new google.ima.AdsLoader(adDisplayContainer);

adsLoader.addEventListener(
google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
onAdsManagerLoaded,
false
);

adsLoader.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
function (adErrorEvent) {
console.error('Ad error:', adErrorEvent.getError());
if (adsManager) adsManager.destroy();
videoContent.play();
},
false
);

var adsRequest = new google.ima.AdsRequest();
adsRequest.adTagUrl = 'https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dlinear&correlator=';
adsRequest.linearAdSlotWidth = 640;
adsRequest.linearAdSlotHeight = 360;
adsRequest.nonLinearAdSlotWidth = 640;
adsRequest.nonLinearAdSlotHeight = 150;

var adsManager;

function onAdsManagerLoaded(adsManagerLoadedEvent) {
adsManager = adsManagerLoadedEvent.getAdsManager(videoContent);

adsManager.addEventListener(google.ima.AdEvent.Type.STARTED, function() {
console.log('Ad started');
});
adsManager.addEventListener(google.ima.AdEvent.Type.COMPLETE, function() {
console.log('Ad completed');
});

try {
adsManager.init(640, 360, google.ima.ViewMode.NORMAL);
adsManager.start();
} catch (adError) {
console.error('AdsManager could not be started:', adError);
videoContent.play();
}
}

function requestAds() {
adsLoader.requestAds(adsRequest);
}
videoContent.addEventListener('play', requestAds, { once: true });
</script>

Explanation:

  • The adsLoader is responsible for loading ads from the ad server.
  • The adsRequest.adTagUrl specifies the ad server URL where the ad tag is located.
  • When ads are successfully loaded, the onAdsManagerLoaded function initializes the ads manager and starts the ad playback.

Error Handling and Retries for Ads

When working with ads, especially from external sources, errors may occur due to network issues, unsupported formats, or other factors. It is important to handle such errors gracefully.

code
player.on('aderror', function(e) {
console.error('Ad failed to load:', e);
alert('Error loading ad. Retrying...');
// Attempt to reload ad or switch to another ad source
});

Explanation:

  • The aderror event listens for ad errors and logs them for debugging.
  • A retry mechanism can be implemented by attempting to reload the ad or switching to a fallback ad source.

Ad Customization and UI Enhancements

To improve the user experience, you can add custom UI elements for ads, such as skip buttons or timers.

Example: Adding Skip Button for Skippable Ads

code
var skipButton = document.createElement('button');
skipButton.textContent = 'Skip Ad';
document.body.appendChild(skipButton);

skipButton.addEventListener('click', function() {
adsManager.skip();
});

Explanation:

  • A skip button is created dynamically and added to the page.
  • When the user clicks the skip button, the ad is skipped using adsManager.skip().