Using Companion Ads with the Ad API

This page describes how to display your companion ads using the Ad API.

Displaying Companion Ads

To display companion ads, first get a reference to an Ad object through any of the AdEvent events dispatched from the AdsManager. We recommend using the AdEvent.STARTED event, as displaying companion ads should coincide with displaying the master ad.

Next, use this Ad object to call getCompanionAds() to get an array of CompanionAd objects. Here you have the option of specifying CompanionAdSelectionSettings, which allows you to set filters on the companion ads for creative type, near fit percentage, resource type, and size criteria. For more information on these settings, see the HTML5 API documentation.

The CompanionAd objects returned by getCompanionAds can now be used to display the companion ads on the page using these guidelines:

  1. Create a companion ad slot <div> of the required size on the page.
  2. In your event handler for the STARTED event, retrieve the Ad object by calling getAd().
  3. Use getCompanionAds() to get a list of companion ads that match both the companion ad slot size and CompanionAdSelectionSettings and have the same sequence number as the master creative. Creatives with a missing sequence attribute are treated as having sequence number 0.
  4. Get the content from a CompanionAd instance and set it as the inner HTMl of that ad slot's <div>.

Sample Code

<div id="companion-ad-300-250" width="300" height="250"></div>

<script type="text/javascript">

  // Listen to the STARTED event.

  function onAdEvent(adEvent) {
    switch (adEvent.type) {
      case google.ima.AdEvent.Type.STARTED:
        // Get the ad from the event.
        var ad = adEvent.getAd();
        var selectionCriteria = new google.ima.CompanionAdSelectionSettings();
        selectionCriteria.resourceType = google.ima.CompanionAdSelectionSettings.ResourceType.STATIC;
        selectionCriteria.creativeType = google.ima.CompanionAdSelectionSettings.CreativeType.IMAGE;
        selectionCriteria.sizeCriteria = google.ima.CompanionAdSelectionSettings.SizeCriteria.IGNORE;
        // Get a list of companion ads for an ad slot size and CompanionAdSelectionSettings
        var companionAds = ad.getCompanionAds(300, 250, selectionCriteria);
        var companionAd = companionAds[0];
        // Get HTML content from the companion ad.
        var content = companionAd.getContent();
        // Write the content to the companion ad slot.
        var div = document.getElementById('companion-ad-300-250');
        div.innerHTML = content;

Send feedback about...

Need help? Visit our support page.