設定 IMA SDK

您可以使用 IMA SDK 輕鬆將多媒體廣告整合至網站和應用程式。IMA SDK 可向任何 符合 VAST 規定的廣告伺服器要求廣告,並管理應用程式中的廣告播放作業。使用 IMA 用戶端 SDK 時,您可以繼續控制內容影片播放,而 SDK 則負責處理廣告播放。廣告會在位於應用程式內容影片播放器頂端的獨立影片播放器中播放。

本指南將說明如何將 IMA SDK 整合至簡易的影片播放器應用程式。如要查看或參考已完成整合的範例,請從 GitHub 下載簡易範例。如果您有興趣使用預先整合 SDK 的 HTML5 播放器,請查看 Video.js 專用的 IMA SDK 外掛程式

IMA 用戶端簡介

實作 IMA 用戶端需要四個主要 SDK 元件,本指南會說明這些元件:

  • AdDisplayContainer:容器物件,可指定 IMA 算繪廣告 UI 元素和評估可視度的所在位置,包括 Active ViewOpen Measurement
  • AdsLoader:要求廣告的物件,並處理廣告請求回應中的事件。您應只例項化一個廣告載入器,這樣一來,您就能在整個應用程式生命週期中重複使用。
  • AdsRequest:定義廣告請求的物件。廣告要求會指定 VAST 廣告代碼的網址,以及其他參數,例如廣告尺寸。
  • AdsManager:包含廣告請求回應、控制廣告播放,以及聆聽 SDK 觸發的廣告事件的物件。

必要條件

在您開始之前,您需要擁有下列項目:

  • 三個空白檔案:
    • index.html
    • style.css
    • ads.js
  • 電腦上已安裝 Python,或用於測試的網路伺服器

1. 啟動開發伺服器

由於 IMA SDK 會使用與載入頁面相同的通訊協定載入依附元件,因此您必須使用網路伺服器測試應用程式。啟動本機開發伺服器最簡單的方法,就是使用 Python 內建的伺服器。

  1. 使用指令列,從含有 index.html 檔案的目錄執行以下指令:
      python -m http.server 8000
  2. 透過網路瀏覽器前往 http://localhost:8000/

您也可以使用任何其他網頁伺服器,例如 Apache HTTP Server

2. 建立簡單的影片播放器

首先,請修改 index.html,建立簡單的 HTML5 影片元素,並在包裝元素中加入觸發播放的按鈕。以下範例會匯入 IMA SDK,並設定 AdDisplayContainer 容器元素。詳情請分別參閱「 匯入 IMA SDK 」和「 建立廣告容器 」兩個步驟。

<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();
});

新增必要的標記,以便載入 style.cssads.js 檔案。接著,修改 styles.css,讓影片播放器在行動裝置上呈現回應式設計。最後,在 ads.js 中宣告變數,並在您點按播放按鈕時觸發影片播放。

請注意,ads.js 程式碼片段包含對 setUpIMA() 的呼叫,該呼叫在「 Initialize the AdsLoader and make an ads request 」一節中定義。

3. 匯入 IMA SDK

接著,請在 index.html 中使用指令碼標記新增 IMA 架構,放在 ads.js 的標記之前。

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

4. 建立廣告容器

在大多數瀏覽器中,IMA SDK 會使用專屬的廣告容器元素,同時顯示廣告和廣告相關的 UI 元素。這個容器的大小必須能從左上角疊加影片元素。adsManager 物件會設定放置在這個容器中的廣告的高度和寬度,因此您不需要手動設定這些值。

如要實作這個廣告容器元素,請先在 video-container 元素中建立新的 div。接著,更新 CSS,將元素置於 video-element 的左上角。最後,請新增 createAdDisplayContainer() 函式,使用新的廣告容器 div 建立 AdDisplayContainer 物件。

<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. 初始化 AdsLoader 並提出廣告請求

如要要求廣告,請建立 AdsLoader 例項。AdsLoader 建構函式會將 AdDisplayContainer 物件做為輸入內容,可用於處理與指定廣告代碼網址相關聯的 AdsRequest 物件。本例中使用的廣告代碼包含 10 秒的片頭廣告。您可以使用 IMA 影片套件檢查器測試這個或任何廣告代碼網址。

最佳做法是在網頁的整個生命週期中,只保留一個 AdsLoader 例項。如要提出其他廣告要求,請建立新的 AdsRequest 物件,但重複使用相同的 AdsLoader。詳情請參閱 IMA SDK 常見問題

使用 AdsLoader.addEventListener 監聽及回應廣告載入和錯誤事件。監聽下列事件:

  • ADS_MANAGER_LOADED
  • AD_ERROR

如要建立 onAdsManagerLoaded()onAdError() 事件監聽器,請參閱下列範例:

/**
 * 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. 回應 AdsLoader 事件

AdsLoader 成功載入廣告時,會發出 ADS_MANAGER_LOADED 事件。剖析傳遞至回呼的事件,以便初始化 AdsManager 物件。AdsManager 會根據廣告代碼網址的回應,載入個別廣告。

請務必處理載入程序中發生的任何錯誤。如果廣告無法載入,請務必確保媒體播放作業在沒有廣告的情況下繼續進行,以免干擾使用者觀看內容。

/**
 * 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();
}

如要進一步瞭解 onAdsManagerLoaded() 函式中設定的事件監聽器,請參閱以下子節:

處理 AdsManager 錯誤

AdsLoader 建立的錯誤處理程序也可以做為 AdsManager 的錯誤處理程序。請參閱事件處理常式,瞭解如何重複使用 onAdError() 函式。

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

處理播放和暫停事件

AdsManager 準備插入廣告以供顯示時,會觸發 CONTENT_PAUSE_REQUESTED 事件。處理這個事件時,請觸發對基礎影片播放器的暫停動作。同樣地,當廣告播放完畢時,AdsManager 會觸發 CONTENT_RESUME_REQUESTED 事件。如要處理這項事件,請重新啟動基礎內容影片的播放作業。

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

如需 onContentPauseRequested()onContentResumeRequested() 函式的定義,請參閱以下範例:

/**
 * 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();
}

處理非線性廣告期間的內容播放作業

AdsManager 會在廣告準備播放時暫停內容影片,但這項行為不適用於非線性廣告,因為在這種情況下,內容會在廣告顯示時繼續播放。

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

如要支援非線性廣告,請監聽 AdsManager 以發出 LOADED 事件。檢查廣告是否為線性廣告,如果不是,請在影片元素上恢復播放。

如要瞭解 onAdLoaded() 函式的定義,請參閱以下範例。

/**
 * 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. 在行動裝置上觸發點擊暫停功能

由於 AdContainer 會疊加影片元素,使用者無法直接與底層播放器互動。這可能會讓行動裝置使用者感到困惑,因為他們預期輕觸影片播放器即可暫停播放。為解決這個問題,IMA SDK 會將 IMA 未處理的任何點擊從廣告疊加層傳遞至 AdContainer 元素,以便處理這些點擊。這項規定不適用於非行動瀏覽器上的線性廣告,因為點按廣告會開啟點閱連結。

如要實作點按暫停功能,請在 on window load 事件監聽器中新增 adContainerClick() 點按處理常式函式。

/**
 * 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. 啟動 AdsManager

如要開始播放廣告,請啟動並開始 AdsManager。如要全面支援行動瀏覽器,您無法自動播放廣告,請在使用者與網頁互動時觸發廣告播放,例如按下播放按鈕。

/**
 * 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. 支援調整播放器大小

如要讓廣告動態調整大小並配合影片播放器的大小,或配合螢幕方向變更,請在回應視窗大小調整事件時呼叫 adsManager.resize()

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);
  }
});

大功告成!您現在可以使用 IMA SDK 請求及顯示廣告。如要進一步瞭解其他進階 SDK 功能,請參閱其他指南或 GitHub 上的範例