設定 IMA SDK

選取平台: HTML5 Android iOS tvOS

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

本指南說明如何將 IMA SDK 整合至簡易影片播放器應用程式。如要查看或按照完整的整合範例操作,請從 GitHub 下載簡易範例。如果您想使用預先整合 SDK 的 HTML5 播放器,請參閱 Video.js 的 IMA SDK 外掛程式。

IMA 用戶端總覽

導入 IMA 用戶端 SDK 涉及四個主要 SDK 元件,本指南將逐一說明:

  • AdDisplayContainer: 容器物件,用於指定 IMA 算繪廣告 UI 元素和評估可視度的位置,包括 Active View 和 Open 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.css 和 ads.js 檔案。接著,修改 styles.css,讓影片播放器能配合行動裝置調整。最後,在 ads.js 中宣告變數,並在點選播放按鈕時觸發影片播放。

請注意,ads.js 程式碼片段包含對 setUpIMA() 的呼叫,該呼叫定義於「初始化 AdsLoader 並發出廣告請求」一節。

3. 匯入 IMA SDK

接著,在 index.html 中,使用指令碼標記在 ads.js 標記前加入 IMA 架構。

<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);
  adsLoader.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR, onAdError);

  // 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&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 元素,以便處理。這不適用於非行動瀏覽器上的線性廣告,因為點按廣告會開啟到達網頁連結。

如要實作點按暫停功能,請在視窗載入事件監聽器中,新增名為 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 上的範例。