開始使用

使用 IMA SDK 即可輕鬆將互動式多媒體廣告整合至您的網站和應用程式。IMA SDK 能向任何 符合 VAST 規定的廣告伺服器請求廣告,並管理您應用程式中的廣告播放。使用 IMA 用戶端 SDK,您即可控管內容影片播放,而 SDK 會處理廣告播放。廣告會在另一個內容影片播放器上方播放影片。

本指南說明如何將 IMA SDK 整合到簡單的影片播放器應用程式中。如果您想查看已完成完成的部分,或是按照我們提供的範例進行整合,請從 GitHub 下載簡易範例。如果您想使用已預先整合 SDK 的 HTML5 播放器,請參閱 Video.js 專用 IMA SDK 外掛程式

IMA 用戶端總覽

用戶端導入 IMA 用戶端時,會涉及本指南中的四個主要 SDK 元件:

  • AdDisplayContainer: 顯示廣告的容器物件。
  • 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 影片元素,其中包含包裝元素,以及可觸發播放的按鈕。此外,請新增必要標記以載入 style.cssads.js 檔案。然後修改 styles.css,將影片播放器調整為適用於行動裝置。最後,在 ads.js 中,在使用者按下播放按鈕時觸發影片播放。

index.html

<!doctype html>
<html lang="en">
  <head>
    <title>IMA HTML5 Simple Demo</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div id="page-content">
      <div id="video-container">
        <video id="video-element">
          <source src="https://storage.googleapis.com/interactive-media-ads/media/android.mp4">
          <source src="https://storage.googleapis.com/interactive-media-ads/media/android.webm">
        </video>
      </div>
      <button id="play-button">Play</button>
    </div>
    <script src="ads.js"></script>
  </body>
</html>

style.css
#page-content {
  position: relative;
  /* this element's width controls the effective height */
  /* of the video container's padding-bottom */
  max-width: 640px;
  margin: 10px auto;
}

#video-container {
  position: relative;
  /* forces the container to match a 16x9 aspect ratio */
  /* replace with 75% for a 4:3 aspect ratio, if needed */
  padding-bottom: 56.25%;
}

#video-element {
  /* forces the contents to fill the container */
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
ads.js
var videoElement;

// On window load, attach an event to the play button click
// that triggers playback on the video element
window.addEventListener('load', function(event) {
  videoElement = document.getElementById('video-element');
  var playButton = document.getElementById('play-button');
  playButton.addEventListener('click', function(event) {
    videoElement.play();
  });
});

完成此步驟後,在瀏覽器中 (透過開發伺服器) 開啟 index.html 時,您應該會看見影片元素,您應該按一下「播放」按鈕觀看影片。

3. 匯入 IMA SDK

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

index.html
...

        </video>
      </div>
      <button id="play-button">Play</button>
    </div>
    <script src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
    <script src="ads.js"></script>
  </body>
</html>

4. 附加網頁和影片播放器處理常式

如要使用 JavaScript 修改影片播放器的行為,請新增會觸發以下動作的事件處理常式:

  • 網頁載入完畢後,請初始化 IMA SDK。
  • 當使用者點選播放按鈕時,載入廣告 (除非已載入廣告)。
  • 調整瀏覽器視窗大小時,請更新影片元素和 adsManager 尺寸,讓網頁在行動裝置上保持回應式狀態
ads.js
var videoElement;
// Define a variable to track whether there are ads loaded and initially set it to false
var adsLoaded = false;

window.addEventListener('load', function(event) {
  videoElement = document.getElementById('video-element');
  initializeIMA();
  videoElement.addEventListener('play', function(event) {
    loadAds(event);
  });
  var playButton = document.getElementById('play-button');
  playButton.addEventListener('click', function(event) {
    videoElement.play();
  });
});

window.addEventListener('resize', function(event) {
  console.log("window resized");
});

function initializeIMA() {
  console.log("initializing IMA");
}

function loadAds(event) {
  // Prevent this function from running on if there are already ads loaded
  if(adsLoaded) {
    return;
  }
  adsLoaded = true;

  // Prevent triggering immediate playback when ads are loading
  event.preventDefault();

  console.log("loading ads");
}

5. 建立廣告容器

在多數瀏覽器中,IMA SDK 會使用專屬的廣告容器元素,同時顯示廣告和廣告相關的 UI 元素。這個容器必須調整大小,以符合影片左上角的元素。這個容器中廣告的高度和寬度是由 adsManager 物件設定,因此您不必手動設定這些值。

如要導入這個廣告容器元素,請先在 video-container 元素中建立新的 div。接著更新 CSS,將元素放在 video-element 的左上角。最後,在 initializeIMA() 函式中載入網頁載入時執行的容器變數。

index.html
...

  <div id="video-container">
    <video id="video-element" controls>
      <source src="https://storage.googleapis.com/interactive-media-ads/media/android.mp4">
      <source src="https://storage.googleapis.com/interactive-media-ads/media/android.webm">
    </video>
    <div id="ad-container"></div>
  </div>

...
style.css
...

#ad-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}
ads.js
var videoElement;
var adsLoaded = false;
var adContainer;

...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
}

6. 初始化 AdsLoader 並提出廣告請求

如要請求一組廣告,請建立 ima.AdsLoader 執行個體。這個執行個體會將 AdDisplayContainer 物件視為輸入內容,並用來處理與指定廣告代碼網址相關聯的 ima.AdsRequest 物件。本範例中使用的廣告代碼包含 10 秒的片頭廣告。您可以使用 IMA 影片套件檢查器,測試任何廣告代碼。

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

ads.js
var videoElement;
var adsLoaded = false;
var adContainer;
var adDisplayContainer;
var adsLoader;

...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
  adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoElement);
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);

  // Let the AdsLoader know when the video has ended
  videoElement.addEventListener('ended', function() {
    adsLoader.contentComplete();
  });

  var 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 = videoElement.clientWidth;
  adsRequest.linearAdSlotHeight = videoElement.clientHeight;
  adsRequest.nonLinearAdSlotWidth = videoElement.clientWidth;
  adsRequest.nonLinearAdSlotHeight = videoElement.clientHeight / 3;

  // Pass the request to the adsLoader to request ads
  adsLoader.requestAds(adsRequest);
}

7. 監聽 AdsLoader 事件

成功載入廣告時,ima.AdsLoader 會發出 ADS_MANAGER_LOADED 事件。剖析傳遞給回呼的事件,以初始化 AdsManager 物件。AdsManager 會依照廣告代碼回應的回應載入個別廣告。

此外,請務必處理載入過程中可能發生的任何錯誤。如果廣告無法載入,請確認媒體播放應繼續播放,不受廣告幹擾,以免干擾使用者體驗。

ads.js
var videoElement;
var adsLoaded = false;
var adContainer;
var adDisplayContainer;
var adsLoader;
var adsManager;

...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
  adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoElement);
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);
  adsLoader.addEventListener(
      google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
      onAdsManagerLoaded,
      false);
  adsLoader.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdError,
      false);

...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  // Instantiate the AdsManager from the adsLoader response and pass it the video element
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);
}

function onAdError(adErrorEvent) {
  // Handle the error logging.
  console.log(adErrorEvent.getError());
  if(adsManager) {
    adsManager.destroy();
  }
}

8. 啟動 AVD

若要開始播放廣告,您必須啟動 AdsManager。為完整支援行動瀏覽器,請由使用者互動觸發。

ads.js
...

function loadAds(event) {
  // prevent this function from running on every play event
  if(adsLoaded) {
    return;
  }
  adsLoaded = true;

  // prevent triggering immediate playback when ads are loading
  event.preventDefault();

  console.log("loading ads");

  // Initialize the container. Must be done via a user action on mobile devices.
  videoElement.load();
  adDisplayContainer.initialize();

  var width = videoElement.clientWidth;
  var height = videoElement.clientHeight;
  try {
    adsManager.init(width, height, google.ima.ViewMode.NORMAL);
    adsManager.start();
  } catch (adError) {
    // Play the video without ads, if an error occurs
    console.log("AdsManager could not be started");
    videoElement.play();
  }
}

...

9. 將 AVD 設為回應式

為了確保廣告能根據影片播放器大小動態調整大小,如果螢幕變更了大小或方向,則視窗大小事件必須呼叫 adsManager.resize()

ads.js
...

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

...

10. 監聽 VAST 事件

AdsManager 也會觸發幾個必須處理的事件。這些事件可用於追蹤狀態變更、觸發內容影片播放及暫停,以及註冊錯誤。

處理錯誤

新增具有相同回呼函式的新事件處理常式,做為 AdsLoader 的錯誤處理常式,可做為 AdsManager 的錯誤處理常式。

ads.js
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);

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

...

觸發播放及暫停事件

AdsManager 準備好插入多媒體廣告時,就會觸發 CONTENT_PAUSE_REQUESTED 事件。觸發基礎影片播放器中的暫停事件,即可處理此事件。同樣地,廣告結束時,AdsManager 會觸發 CONTENT_RESUME_REQUESTED 事件。請重新啟動基礎內容影片播放作業,以處理此事件。

ads.js
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);

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

...

function onContentPauseRequested() {
  videoElement.pause();
}

function onContentResumeRequested() {
  videoElement.play();
}

在行動裝置上觸發點擊暫停功能

AdContainer 會重疊影片元素,因此使用者無法直接與基礎播放器互動。這會對行動裝置使用者造成混淆,並預期使用者只要輕觸影片播放器即可暫停播放。為解決這個問題,IMA SDK 會將非 IMA 處理的任何點擊,傳送至 AdContainer 元素,藉此處理這類點擊。這項設定不適用於非行動瀏覽器中的線性廣告,因為點擊廣告後會開啟點閱連結。

如要實作點擊暫停,請在 AdContainer 中新增點擊處理常式,並觸發基礎影片的播放或暫停事件。

ads.js
...

function initializeIMA() {
  console.log("initializing IMA");
  adContainer = document.getElementById('ad-container');
  adContainer.addEventListener('click', adContainerClick);
  adDisplayContainer = new google.ima.AdDisplayContainer(adContainer, videoElement);
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);

...

function adContainerClick(event) {
  console.log("ad container clicked");
  if(videoElement.paused) {
    videoElement.play();
  } else {
    videoElement.pause();
  }
}

...

觸發非線性廣告的播放

AdsManager 會在廣告準備好播放時暫停內容影片,但這個行為不適用於非線性廣告,因此廣告會在廣告顯示時繼續播放。如要支援非線性廣告,請監聽 AdsManager 來發出 LOADED 事件,接著,檢查廣告是否為線性,如果沒有,則要繼續播放影片元素。

ads.js
...

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);

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

...

function onAdLoaded(adEvent) {
  var ad = adEvent.getAd();
  if (!ad.isLinear()) {
    videoElement.play();
  }
}

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