Skip to content

Instantly share code, notes, and snippets.

@astein
Last active August 18, 2022 16:02
Show Gist options
  • Save astein/32f776278856e36474a1 to your computer and use it in GitHub Desktop.
Save astein/32f776278856e36474a1 to your computer and use it in GitHub Desktop.
Example of using Google IMA SDK for HTML5
// video DOM inside creative
//<div id="videoContainer">
// <video id="videoContainer"></video>
//</div>
// load IMA SDK at init load time
$.getScript('//imasdk.googleapis.com/js/sdkloader/ima3.js');
// usage: startVideo( /* vast tag url */ );
// set width and height according to video size in creative
var VIDEO_WIDTH = 600;
var VIDEO_HEIGHT = 380;
var adsManager;
var adsLoader;
var adDisplayContainer;
var intervalTimer;
var videoContent = document.getElementById('videoContainer');
function startVideo(vast_tag) {
requestAds(vast_tag);
}
function createAdDisplayContainer() {
// We assume the adContainer is the DOM id of the element that will house
// the ads.
adDisplayContainer =
new google.ima.AdDisplayContainer(
document.getElementById('adContainer'), videoContent);
}
function requestAds(vast_tag) {
// Create the ad display container.
createAdDisplayContainer();
// Initialize the container. Must be done via a user action on mobile devices.
adDisplayContainer.initialize();
videoContent.load();
// Create ads loader.
adsLoader = new google.ima.AdsLoader(adDisplayContainer);
// Set VPAID Mode to Enabled
adsLoader.getSettings().setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
adsLoader.getSettings().setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.INSECURE);
// Listen and respond to ads loaded and error events.
adsLoader.addEventListener(
google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
onAdsManagerLoaded,
false);
adsLoader.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
onAdError,
false);
// Request video ads.
var adsRequest = new google.ima.AdsRequest();
// autoplay ad
adsRequest.setAdWillAutoPlay(true);
adsRequest.adTagUrl = vast_tag;
// Specify the linear and nonlinear slot sizes. This helps the SDK to
// select the correct creative if multiple are returned.
adsRequest.linearAdSlotWidth = VIDEO_WIDTH;
adsRequest.linearAdSlotHeight = VIDEO_HEIGHT;
adsRequest.nonLinearAdSlotWidth = VIDEO_WIDTH;
adsRequest.nonLinearAdSlotHeight = VIDEO_HEIGHT;
adsLoader.requestAds(adsRequest);
}
function onAdsManagerLoaded(adsManagerLoadedEvent) {
// Get the ads manager.
var adsRenderingSettings = new google.ima.AdsRenderingSettings();
adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true;
adsRenderingSettings.bitrate = 1000;
// videoContent should be set to the content video element.
adsManager = adsManagerLoadedEvent.getAdsManager(
videoContent, adsRenderingSettings);
// Add listeners to the required events.
adsManager.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
onAdError);
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
onContentPauseRequested);
adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
onContentResumeRequested);
adsManager.addEventListener(
google.ima.AdEvent.Type.ALL_ADS_COMPLETED,
onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.CLICK,
onAdEvent);
// Listen to any additional events, if necessary.
adsManager.addEventListener(
google.ima.AdEvent.Type.LOADED,
onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.STARTED,
onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.COMPLETE,
onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.FIRST_QUARTILE,
onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.MIDPOINT,
onAdEvent);
adsManager.addEventListener(
google.ima.AdEvent.Type.THIRD_QUARTILE,
onAdEvent);
try {
// Initialize the ads manager. Ad rules playlist will start at this time.
adsManager.init(VIDEO_WIDTH, VIDEO_HEIGHT, google.ima.ViewMode.NORMAL);
// Call play to start showing the ad. Single video and overlay ads will
// start at this time; the call will be ignored for ad rules.
adsManager.start();
} catch (adError) {
// An error may be thrown if there was a problem with the VAST response.
videoContent.play();
}
}
function onAdEvent(adEvent) {
// Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
// don't have ad object associated.
var ad = adEvent.getAd();
switch (adEvent.type) {
case google.ima.AdEvent.Type.LOADED:
// console.log('loaded');
// This is the first event sent for an ad - it is possible to
// determine whether the ad is a video ad or an overlay.
if (!ad.isLinear()) {
// Position AdDisplayContainer correctly for overlay.
// Use ad.width and ad.height.
videoContent.play();
}
break;
case google.ima.AdEvent.Type.STARTED:
// only hide the content element (video overlay) when ad starts.
$('#contentElement').hide();
TXM.api.track('multimedia', 'video_started', 'vast_video');
// This event indicates the ad has started - the video player
// can adjust the UI, for example display a pause button and
// remaining time.
if (ad.isLinear()) {
// For a linear ad, a timer can be started to poll for
// the remaining time.
intervalTimer = setInterval(
function() {
var remainingTime = adsManager.getRemainingTime();
},
300); // every 300ms
}
break;
case google.ima.AdEvent.Type.COMPLETE:
TXM.api.track('multimedia', 'video_completed', 'vast_video');
if (ad.isLinear()) {
clearInterval(intervalTimer);
}
break;
case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
break;
case google.ima.AdEvent.Type.CLICK:
(function() {
var prop;
var currentAd = adEvent.getAd();
var clickThroughUrl;
// Clickthrough parameter is obfuscated in IMA3. We loopthrough the properties of the
// ad and search for a "clickThroughUrl" attribute. We track it if we find one.
for(prop in ad) {
clickThroughUrl = ad[prop].clickThroughUrl;
if (clickThroughUrl !== undefined && clickThroughUrl !== null) {
break;
}
}
if (clickThroughUrl) {
TXM.api.track('navigation', 'external_page', 'vast_clickthrough');
}
}());
break;
// video quartile tracking
case google.ima.AdEvent.Type.FIRST_QUARTILE:
TXM.api.track('multimedia', 'video_first_quartile', 'vast_video');
break;
case google.ima.AdEvent.Type.MIDPOINT:
TXM.api.track('multimedia', 'video_second_quartile', 'vast_video');
break;
case google.ima.AdEvent.Type.THIRD_QUARTILE:
TXM.api.track('multimedia', 'video_third_quartile', 'vast_video');
break;
}
}
function onAdError(adErrorEvent) {
adsManager.destroy();
}
function onContentPauseRequested() {
videoContent.pause();
}
@lynxerzhang
Copy link

hi, in "Google IMA SDK for HTML5" examples

I found title 'Request video ads' with below code

// Request video ads.
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=';

I want to ask what is adTagUrl , and where it come from? and I found your example is not use it?

@pescweb
Copy link

pescweb commented Jul 11, 2019

@diglez
Copy link

diglez commented Mar 25, 2020

Hi! I am trying to get a VAST tag to autoplay on page load.
I have this for my video content:
<video id="content" class=${styles.content} playsInLine autoPlay >

and I have set:
adsRequest.setAdWillAutoPlay(true);

but the ad is not autoplaying... I have tried removing and keeping playsinline, I have tried camel case and all lowercase for both playsinline and autoplay, I have tried to add muted, but nothing seems to work.

Any ideas on what it could be?
(this is a react app by the way, if that makes a difference)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment