使用入门

Ad Placement API 支持预缓存/预加载插页式广告。开发者可使用该 API 来表示游戏或其他互动式媒体内容中可能存在的广告插播时间点/时刻,但需要委托 Google 针对何时展示广告以及要展示哪些广告做出准确决定。

Ad Placement API 旨在帮助 AdSense 开发者在 HTML5 网页游戏、超级应用或其他互动式媒体内容中使用插页式广告。本指南介绍了如何将 Ad Placement API 集成到简单的游戏中。

前提条件

在开始之前,您需要完成以下操作:

  • 创建以下空文件:
    • index.html
    • game.js
  • 在用于测试的计算机或网络服务器上安装 Python。

1. 启动开发服务器

由于 Ads Placement API 加载依赖项所用的协议与其加载时所在网页使用的协议相同,因此您需要使用网络服务器来测试应用。要启动本地开发服务器,最简单的方法是使用 Python 的内置服务器。

  1. 在您的 index.html 文件所在的目录下使用命令行运行以下命令:
    python -m http.server 8000
  2. 在网络浏览器中,转到 http://localhost:8000/

您也可以使用任何其他网络服务器,例如 Apache HTTP Server

2. 制作一个简单的 HTML5 画布游戏

修改 index.html,以创建一个简单的 HTML5 画布元素,以及一个用于触发游戏的按钮。此外,还要添加必要的脚本标记来加载 game.js 文件。

index.html

<!doctype html>
<html lang="en">
  <head>
    <title>Ad Placement API HTML5 simple demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <canvas id="gameContainer" height="300px" width="300px"></canvas>
    <button id="playButton">Play</button>
    <button style="display:none" id="headsButton">Heads</button>
    <button style="display:none" id="tailsButton">Tails</button>

    <script src="game.js"></script>
  </body>
</html>

修改 game.js,让用户能在点击“开始游戏”按钮后玩抛硬币游戏。

game.js
class Game {
  constructor() {
    // Define variables
    this.score = 0;
    this.choice = '';

    this.canvas = document.getElementById('gameContainer').getContext('2d');
    this.canvas.font = '24px Arial';

    this.playButton = document.getElementById('playButton');
    this.headsButton = document.getElementById('headsButton');
    this.tailsButton = document.getElementById('tailsButton');

    // On click listeners for the game's buttons.
    this.playButton.addEventListener('click', () => {
      this.erase();
      this.play();
    });

    this.headsButton.addEventListener('click', () => {
      this.choice = 'Heads';
      this.flipCoin();
    });

    this.tailsButton.addEventListener('click', () => {
      this.choice = 'Tails';
      this.flipCoin();
    });

    this.erase();
  }

  // Start the game
  play() {
    this.score = 0;
    this.canvas.fillText('Score: ' + this.score, 8, 26);
    this.canvas.fillText('Heads or Tails?', 66, 150);
    this.playButton.style.display = 'none';
    this.headsButton.style.display = 'inline-block';
    this.tailsButton.style.display = 'inline-block';
  }

  // Flip the coin
  flipCoin() {
    this.headsButton.disabled = true;
    this.tailsButton.disabled = true;
    this.erase();
    this.canvas.fillText('Score: ' + this.score, 8, 26);
    this.canvas.fillText('Flipping coin . . .', 60, 150);

    setTimeout(() => { this.coinLanded() }, 2000);
  }

  // Logic for when the coin lands
  coinLanded() {
    this.headsButton.disabled = false;
    this.tailsButton.disabled = false;
    let sideUp;
    if(Math.random() < 0.5) {
      sideUp = 'Heads';
    } else {
      sideUp = 'Tails';
    }

    if (sideUp === this.choice ) {
      this.win(sideUp);
    } else {
      this.lose(sideUp);
    }
  }

  // Guess the flip correctly
  win(sideUp) {
    this.erase();
    this.score += 1;
    this.canvas.fillText('Score: ' + this.score, 8, 26);
    this.canvas.fillText('It was ' + sideUp + '!', 66, 150);
    this.canvas.fillText('Guess again', 70, 200);
  }

  // Guess the flip incorrectly
  lose(sideUp) {
    this.erase();
    this.canvas.fillText('Sorry, it was ' + sideUp, 50, 100);
    this.canvas.fillText('Your score was ' + this.score, 50, 150);
    this.canvas.fillText('Want to play again?', 45, 200);

    this.playButton.style.display = 'inline-block';
    this.headsButton.style.display = 'none';
    this.tailsButton.style.display = 'none';
  }

  // Erase the canvas
  erase() {
    this.canvas.fillStyle = '#ADD8E6';
    this.canvas.fillRect(0, 0, 300, 300);
    this.canvas.fillStyle = '#000000';
  }
}

const game = new Game();

完成此步骤后,当您在浏览器中(通过开发服务器)打开 index.html 时,应该可以看到游戏画布和“开始游戏”按钮。如果您点击 Play,应该就能开始玩抛硬币游戏。

3. 导入 Ad Placement API

接下来,在 index.html 中插入一个脚本标记,将其放在 game.js 对应的标记之前,以便将 Ad Placement API 添加到游戏中。

index.html
...

    <canvas id="gameContainer" height="300px" width="300px"></canvas>
    <button id="playButton">Play</button>
    <button style="display:none" id="headsButton">Heads</button>
    <button style="display:none" id="tailsButton">Tails</button>

    <script async
      data-ad-client="ca-pub-123456789"
      data-adbreak-test="on"
      src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
    </script>

    <script>window.adsbygoogle = window.adsbygoogle || [];
      const adBreak =  adConfig = function(o) {adsbygoogle.push(o);}
    </script>
    
    <script src="game.js"></script>
  </body>
</html>

4. 调用 adConfig()

adConfig() 调用会将游戏的当前配置传递给 Ad Placement API。然后,该 API 可以使用这些信息过滤要请求的广告类型,以确保所请求的广告适合游戏(例如,如果游戏启用了声音,则请求需要声音的视频广告)。每当此配置更改时(如用户将游戏静音或取消静音),都应调用 adConfig()。在游戏的构造函数中调用 adConfig(),然后添加一个按钮以便使游戏静音和取消静音,这会再一次调用 adConfig()

目前,adConfig() 只接收 sound 参数,该参数接受 'on''off' 这两个值。如果未设置声音,则默认为 off。该 API 的未来版本中将包含更多参数。

game.js
class Game {
  constructor() {
    // Define variables
    this.score = 0;
    this.choice = '';
    this.muted = false;

    this.canvas = document.getElementById('gameContainer').getContext('2d');
    this.canvas.font = '24px Arial';

    this.playButton = document.getElementById('playButton');
    this.headsButton = document.getElementById('headsButton');
    this.tailsButton = document.getElementById('tailsButton');
    this.muteButton = document.getElementById('muteButton');

    adConfig({
      sound: 'on',
    });

    // On click listeners for the game's buttons.
    this.playButton.addEventListener('click', () => {
      this.erase();
      this.play();
    });

    this.headsButton.addEventListener('click', () => {
      this.choice = 'Heads';
      this.flipCoin();
    });

    this.tailsButton.addEventListener('click', () => {
      this.choice = 'Tails';
      this.flipCoin();
    });

    this.muteButton.addEventListener('click', () => {
      var soundString = this.muted ? 'on' : 'off';
      this.muteButton.innerHTML = this.muted ? 'Mute sound' : 'Un-mute sound';
      this.muted = !this.muted;
      adConfig({
        sound: soundString,
      });
    });

    this.erase();
  ...

现在,将静音按钮添加到您的 HTML 文件中。

index.html
...

    <canvas id="gameContainer" height="300px" width="300px"></canvas>
    <button id="playButton">Play</button>
    <button style="display:none" id="headsButton">Heads</button>
    <button style="display:none" id="tailsButton">Tails</button>
    <button id="muteButton">Mute sound</button>

    <script async
      data-ad-client="ca-pub-123456789"
      data-adbreak-test="on"
      src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
    </script>
    ...

5. 在游戏结束时调用 adBreak()

adBreak() 调用可定义广告展示位置,并接收一个名为 placement config 的对象,此对象指定了在游戏结束这一刻展示广告所需的所有内容。若要支持不同类型的广告,您需要初始化 placement config 的不同子集。如需了解这些子集,请参阅 adBreak placement config 指南

adBreak() 调用可定义广告的展示位置,也就是展示广告的机会。广告是否能真正展示取决于多种因素:

  • 您声明的广告展示位置的类型。
  • 在此广告展示位置之前是否出现过合适的用户互动。
  • 是否存在适合向当前玩家展示的广告,即满足以下条件的广告:
    • 与玩家有关。
    • 与玩家的数据隐私和意见征求设置一致。
  • 用户近期看到的广告数量。
  • 您为此游戏配置的控制设置,可通过以下任一方法进行控制:
    • 标记中的提示。
    • AdSense 中的控件(请注意:AdSense 中的控件会随着时间的推移而变化)。

在本指南中,我们将添加代码,以更在重新开始游戏时展示插页式广告。为此,需要在 play() 函数中调用 adBreak(),这种调用只会在玩家玩完一次游戏后发生。在用户执行操作(如点击“开始游戏”按钮)时,系统必须调用 adBreak(),否则 API 将无法请求和展示广告。此外,还要创建要在广告插播时间点之前和之后调用的函数,这些函数将用在 adBreak() placement config 中。请务必注意,只有在找到合适的广告时,系统才会调用 beforeBreakafterBreak 函数。

game.js
class Game {
  constructor() {
    // Define variables
    this.score = 0;
    this.choice = '';
    this.muted = false;
    this.shouldShowAdOnPlay = false;

...

  // Start the game
  play() {
    if (this.shouldShowAdOnPlay) {
      this.shouldShowAdOnPlay = false;

      adBreak({
        type: 'next',  // ad shows at start of next level
        name: 'restart-game',
        beforeBreak: () => { this.disableButtons(); },  // You may also want to mute the game's sound.
        afterBreak: () => { this.enableButtons(); },    // resume the game flow.
      });
    }

    this.score = 0;
    this.canvas.fillText('Score: ' + this.score, 8, 26);
    this.canvas.fillText('Heads or Tails?', 66, 150);
    this.playButton.style.display = 'none'
    this.headsButton.style.display = 'inline-block'
    this.tailsButton.style.display = 'inline-block'
  }

...

  // Guess the flip incorrectly
  lose(sideUp) {
    this.erase()
    this.canvas.fillText('Sorry, it was ' + sideUp, 50, 100);
    this.canvas.fillText('Your score was ' + this.score, 50, 150);
    this.canvas.fillText('Want to play again?', 45, 200);

    this.playButton.style.display = 'inline-block'
    this.headsButton.style.display = 'none'
    this.tailsButton.style.display = 'none'
    this.shouldShowAdOnPlay = true;
  }

...

  // Erase the canvas
  erase() {
    this.canvas.fillStyle = '#ADD8E6';
    this.canvas.fillRect(0, 0, 300, 300);
    this.canvas.fillStyle = '#000000';
  }

  enableButtons() {
    this.playButton.disabled = false;
    this.headsButton.disabled = false;
    this.tailsButton.disabled = false;
  }

  disableButtons() {
    this.playButton.disabled = true;
    this.headsButton.disabled = true;
    this.tailsButton.disabled = true;
  }

}

const game = new Game();

您的应用现在正在创建用于展示广告的广告展示位置!除了游戏结尾处,您自己的应用可能还有其他适合展示广告的位置。在这些位置调用 adBreak() 的操作应该与本指南中的操作类似。在发布应用之前,请务必移除 index.html 中的 data-adbreak-test="on" 行,以免在正式版中使用测试设置。