Set up the IMA SDK

IMA SDKs make it easy to integrate multimedia ads into your websites and apps. IMA SDKs can request ads from any VAST-compliant ad server and manage ad playback in your apps. With IMA client-side SDKs, you maintain control of content video playback, while the SDK handles ad playback. Ads play in a separate video player positioned on top of the app's content video player.

This guide demonstrates how to integrate the IMA SDK into a simple video player app. If you would like to view or follow along with a completed sample integration, download the simple example from GitHub. If you're interested in an HTML5 player with the SDK pre-integrated, check out the IMA SDK Plugin for Video.js.

IMA client-side overview

Implementing IMA client-side involves four main SDK components, which are demonstrated in this guide:

  • AdDisplayContainer: A container object that specifies where IMA renders ad UI elements and measures viewability, including Active View and Open Measurement.
  • AdsLoader: An object that requests ads and handles events from ads request responses. You should only instantiate one ads loader, which can be reused throughout the life of the application.
  • AdsRequest: An object that defines an ads request. Ads requests specify the URL for the VAST ad tag, as well as additional parameters, such as ad dimensions.
  • AdsManager: An object that contains the response to the ads request, controls ad playback, and listens for ad events fired by the SDK.

Prerequisites

Before you begin, you'll need the following:

  • Three empty files:
    • index.html
    • style.css
    • ads.js
  • Python installed on your computer, or a web server to use for testing

1. Start a development server

Since the IMA SDK loads dependencies using the same protocol as the page from which it's loaded, you need to use a web server to test your app. The simplest way to start a local development server is to use Python's built-in server.

  1. Using a command line, from the directory that contains your index.html file run:
      python -m http.server 8000
  2. In a web browser, go to http://localhost:8000/

You can also use any other web server, such as the Apache HTTP Server.

2. Create a simple video player

First, modify index.html to create a simple HTML5 video element, contained in a wrapping element, and a button to trigger playback. The following example imports the IMA SDK and sets up the AdDisplayContainer container element. For more details, see the Import the IMA SDK and Create the ad container steps respectively.

<html>
  <head>
    <title>IMA HTML5 Simple Demo</title>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <div id="mainContainer">
      <div id="content">
        <video id="contentElement">
          <source src="https://storage.googleapis.com/gvabox/media/samples/stock.mp4"></source>
        </video>
      </div>
      <div id="adContainer"></div>
    </div>
    <button id="playButton">Play</button>
    <script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
    <script src="ads.js"></script>
  </body>
</html>
#mainContainer {
  position: relative;
  width: 640px;
  height: 360px;
}

#content {
  position: absolute;
  top: 0;
  left: 0;
  width: 640px;
  height: 360px;
}

#contentElement {
  width: 640px;
  height: 360px;
  overflow: hidden;
}

#playButton {
  margin-top:10px;
  vertical-align: top;
  width: 350px;
  height: 60px;
  padding: 0;
  font-size: 22px;
  color: white;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
  background: #2c3e50;
  border: 0;
  border-bottom: 2px solid #22303f;
  cursor: pointer;
  -webkit-box-shadow: inset 0 -2px #22303f;
  box-shadow: inset 0 -2px #22303f;
}
let adsManager;
let adsLoader;
let adDisplayContainer;
let isAdPlaying;
let isContentFinished;
let playButton;
let videoContent;
let adContainer;

// On window load, attach an event to the play button click
// that triggers playback of the video element.
window.addEventListener('load', function(event) {
  videoContent = document.getElementById('contentElement');
  adContainer = document.getElementById('adContainer');
  adContainer.addEventListener('click', adContainerClick);
  playButton = document.getElementById('playButton');
  playButton.addEventListener('click', playAds);
  setUpIMA();
});

Add the necessary tags to load the style.css and ads.js files. Then, modify styles.css to make the video player responsive for mobile devices. Finally, in ads.js, declare your variables and trigger video playback when you click the play button.

Note that the ads.js code snippet contains a call to setUpIMA(), which is defined in the Initialize the AdsLoader and make an ads request section.

3. Import the IMA SDK

Next, add the IMA framework using a script tag in index.html, before the tag for ads.js.

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

4. Create the ad container

In most browsers, the IMA SDK uses a dedicated ad container element for displaying both ads and ad-related UI elements. This container must be sized to overlay the video element from the top-left corner. The height and width of the ads placed in this container are set by the adsManager object, so you don't need to set these values manually.

To implement this ad container element, first create a new div within the video-container element. Then, update the CSS to position the element at the top-left corner of the video-element. Finally, add the createAdDisplayContainer() function to create the AdDisplayContainer object using the new ad container div.

<div id="adContainer"></div>
#adContainer {
  position: absolute;
  top: 0;
  left: 0;
  width: 640px;
  height: 360px;
}
/**
 * Sets the 'adContainer' div as the IMA ad display container.
 */
function createAdDisplayContainer() {
  adDisplayContainer = new google.ima.AdDisplayContainer(
      document.getElementById('adContainer'), videoContent);
}

5. Initialize the AdsLoader and make an ads request

In order to request ads, create an AdsLoader instance. The AdsLoader constructor takes an AdDisplayContainer object as an input and can be used to process AdsRequest objects associated with a specified ad tag URL. The ad tag used in this example contains a 10-second pre-roll ad. You can test this, or any, ad tag URL using the IMA Video Suite Inspector.

As a best practice, only maintain one instance of AdsLoader for the entire lifecycle of a page. To make additional ad requests, create a new AdsRequest object, but re-use the same AdsLoader. For more information, see the IMA SDK FAQ.

Listen and respond to ads loaded and error events using AdsLoader.addEventListener. Listen to the following events:

  • ADS_MANAGER_LOADED
  • AD_ERROR

To create the onAdsManagerLoaded() and onAdError() listeners, see the following example:

/**
 * Sets up IMA ad display container, ads loader, and makes an ad request.
 */
function setUpIMA() {
  // Create the ad display container.
  createAdDisplayContainer();
  // Create ads loader.
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);
  // 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);

  // An event listener to tell the SDK that our content video
  // is completed so the SDK can play any post-roll ads.
  const contentEndedListener = function() {
    // An ad might have been playing in the content element, in which case the
    // content has not actually ended.
    if (isAdPlaying) return;
    isContentFinished = true;
    adsLoader.contentComplete();
  };
  videoContent.onended = contentEndedListener;

  // Request video ads.
  const adsRequest = new google.ima.AdsRequest();
  adsRequest.adTagUrl = 'https://pubads.g.doubleclick.net/gampad/ads?' +
      'iu=/21775744923/external/single_ad_samples&sz=640x480&' +
      'cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90&gdfp_req=1&' +
      'output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=';

  // Specify the linear and nonlinear slot sizes. This helps the SDK to
  // select the correct creative if multiple are returned.
  adsRequest.linearAdSlotWidth = 640;
  adsRequest.linearAdSlotHeight = 400;

  adsRequest.nonLinearAdSlotWidth = 640;
  adsRequest.nonLinearAdSlotHeight = 150;

  adsLoader.requestAds(adsRequest);
}

6. Respond to AdsLoader events

When the AdsLoader successfully loads ads, it emits an ADS_MANAGER_LOADED event. Parse the event passed to the callback to initialize the AdsManager object. The AdsManager loads the individual ads as defined by the response to the ad tag URL.

Ensure you handle any errors that occur during the loading process. If ads don't load, make sure that media playback continues without ads to avoid interfering with the user viewing the content.

/**
 * Handles the ad manager loading and sets ad event listeners.
 * @param {!google.ima.AdsManagerLoadedEvent} adsManagerLoadedEvent
 */
function onAdsManagerLoaded(adsManagerLoadedEvent) {
  // Get the ads manager.
  const adsRenderingSettings = new google.ima.AdsRenderingSettings();
  adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true;
  // 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.LOADED, onAdLoaded);
}

/**
 * Handles ad errors.
 * @param {!google.ima.AdErrorEvent} adErrorEvent
 */
function onAdError(adErrorEvent) {
  // Handle the error logging.
  console.log(adErrorEvent.getError());
  adsManager.destroy();
}

For more details about the listeners set in the onAdsManagerLoaded() function, see the following sub-sections:

Handle AdsManager errors

The error handler created for the AdsLoader can also serve as the error handler for the AdsManager. See the event handler reusing the onAdError() function.

adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, onAdError);

Handle play and pause events

When the AdsManager is ready to insert an ad for display, it fires the CONTENT_PAUSE_REQUESTED event. Handle this event by triggering a pause on the underlying video player. Similarly, when an ad completes, the AdsManager fires the CONTENT_RESUME_REQUESTED event. Handle this event by restarting playback on the underlying content video.

adsManager.addEventListener(
    google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, onContentPauseRequested);
adsManager.addEventListener(
    google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
    onContentResumeRequested);

For definitions of the onContentPauseRequested() and onContentResumeRequested() functions, see the following example:

/**
 * Pauses video content and sets up ad UI.
 */
function onContentPauseRequested() {
  isAdPlaying = true;
  videoContent.pause();
  // This function is where you should setup UI for showing ads (for example,
  // display ad timer countdown, disable seeking and more.)
  // setupUIForAds();
}

/**
 * Resumes video content and removes ad UI.
 */
function onContentResumeRequested() {
  isAdPlaying = false;
  if (!isContentFinished) {
    videoContent.play();
  }
  // This function is where you should ensure that your UI is ready
  // to play content. It is the responsibility of the Publisher to
  // implement this function when necessary.
  // setupUIForContent();
}

Handle content playback during non-linear ads

The AdsManager pauses the content video when an ad is ready to play, but this behavior doesn't account for non-linear ads, where the content continues to play while the ad is displayed.

adsManager.addEventListener(google.ima.AdEvent.Type.LOADED, onAdLoaded);

To support non-linear ads, listen for the AdsManager to emit the LOADED event. Check if the ad is linear, and if not, resume playback on the video element.

For the definition of the onAdLoaded() function, see the following example.

/**
 * Handles ad loaded event to support non-linear ads. Continues content playback
 * if the ad is not linear.
 * @param {!google.ima.AdEvent} adEvent
 */
function onAdLoaded(adEvent) {
  let ad = adEvent.getAd();
  if (!ad.isLinear()) {
    videoContent.play();
  }
}

7. Trigger click-to-pause on mobile devices

Since the AdContainer overlays the video element, users cannot interact directly with the underlying player. This can confuse users on mobile devices, who expect to be able to tap a video player to pause playback. To address this issue, the IMA SDK passes any clicks that are not handled by IMA from the ad overlay to the AdContainer element, where they can be handled. This does not apply to linear ads on non-mobile browsers, as clicking the ad opens the clickthrough link.

To implement click-to-pause, add the adContainerClick() click handler function called in the on window load listener.

/**
 * Handles clicks on the ad container to support expected play and pause
 * behavior on mobile devices.
 * @param {!Event} event
 */
function adContainerClick(event) {
  console.log("ad container clicked");
  if(videoContent.paused) {
    videoContent.play();
  } else {
    videoContent.pause();
  }
}

8. Start the AdsManager

To start ad playback, initiate and start the AdsManager. To fully support mobile browsers, where you cannot automatically play ads, trigger ad playback from user interactions with the page, like clicking the play button.

/**
 * Loads the video content and initializes IMA ad playback.
 */
function playAds() {
  // Initialize the container. Must be done through a user action on mobile
  // devices.
  videoContent.load();
  adDisplayContainer.initialize();

  try {
    // Initialize the ads manager. This call starts ad playback for VMAP ads.
    adsManager.init(640, 360);
    // Call play to start showing the ad. Single video and overlay ads will
    // start at this time; the call will be ignored for VMAP ads.
    adsManager.start();
  } catch (adError) {
    // An error may be thrown if there was a problem with the VAST response.
    videoContent.play();
  }
}

9. Support player resizing

For ads to dynamically resize and match a video player's size, or to match changes to the screen orientation, call adsManager.resize() in response to window resize events.

window.addEventListener('resize', function(event) {
  console.log("window resized");
  if(adsManager) {
    let width = videoContent.clientWidth;
    let height = videoContent.clientHeight;
    adsManager.resize(width, height, google.ima.ViewMode.NORMAL);
  }
});

That's it! You're now requesting and displaying ads with the IMA SDK. To learn about more advanced SDK features, see the other guides or the samples on GitHub.