開始使用

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 中的指令碼標記,在 ads.js 的標記前方加入 IMA 架構。

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. 啟動 GTFS

如要開始播放廣告,您必須開始播放 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. 將 AD 設為回應式

為確保廣告能配合影片播放器的大小動態調整大小,如果螢幕會改變尺寸或方向,視窗大小事件就必須呼叫 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. 監聽 AD 事件

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 範例