# Use the Ad Placement API

The Ad Placement API contains two functions: `adBreak()` and `adConfig()`,
defined in the following global namespace. Most of the arguments are functions
you provide that lets you handle the key steps of preparing for and displaying
an ad:

    adBreak({
       type: '<type>',                      // The type of this placement
       name: '<name>',                      // A descriptive name for this placement
       beforeAd: () => {},                  // Prepare for the ad. Mute and pause the game flow
       afterAd: () => {},                   // Resume the game and un-mute the sound
       beforeReward: (showAdFn) => {},      // Show reward prompt (call showAdFn() if clicked)
       adDismissed: () => {},               // Player dismissed the ad before completion
       adViewed: () => {},                  // Ad was viewed and closed
       adBreakDone: (placementInfo) => {},  // Always called (if provided) even if an ad didn't show
    });

    adConfig({
       preloadAdBreaks: 'on|auto',      // Should ads always be preloaded
       sound: 'on|off',                 // Is sound currently enabled within the game
    });

These functions are used to place and configure ads within your game. The
arguments shown above are the only valid arguments that can be passed to these
functions. Different types of ads require different subsets of these
arguments as detailed below.

`adBreak()` is the key function for placing ads within your game. It defines an
*ad placement* and takes an object called a *placement config* that specifies
everything required to show an ad.

The `adBreak()` function defines a placement where an ad *could* be shown.
Whether an ad actually shows depends on factors such as the following:

- **The type of ad placement that you declared**
  - Is this ad at the start of the game? Between levels? At a moment when the player has paused the game?
- **Whether a suitable ad exists for the current player**
  - Is this ad relevant to them?
  - Is it consistent with their data privacy and consent settings?
- **The number of ads the player has seen recently**
- **The control settings---for example, ad frequency, you've configured for this game**
  - Either as hints in the tag, or,
  - Within AdSense---note that the controls available in AdSense will evolve over time.

The kind of ad that shows also depends on similar factors.

Note that a call to `adBreak()` might not show an ad at all. It simply declares
a place where an ad *could* be shown.

This is unlike traditional APIs in which your code always knows if an ad is
available, and you decide within the game whether to show it. This approach of
letting the Ad Placement API decide if an ad shows in a particular placement is
a pattern that is sometimes referred to as "inversion of control".

The reason we're transitioning our games API to this model is firstly, it
shortens the code you have to write within your game. Secondly, it makes it
easier to deliver policy compliant placements with a great user experience,
which in turn has allowed us to deliver some of our highest performing formats
to games publishers. Lastly, it more cleanly separates the process of placing
ads in your game from the monetization decisions about the type and number of
ads to show.

We want you to be able to change your monetization settings and control the user
experience without having to edit and release a new version of your game,
initially by specifying hints in the tag. But in future releases, we will be
able to provide controls directly in the AdSense and AdMob frontends.

## Interstitials

An interstitial ad is a full screen ad that can show at different moments within
your game, such as when the player starts the game, or after the player
completes a level. It pauses the game, covers the entire document, and the
player can choose to click the ad (in which case the ad shows in a different tab
of their browser) or to dismiss it which allows them to proceed with the game.

> [!NOTE]
> **Note:** An interstitial can be shown before your game has even loaded its user interface. This kind of ad is called a preroll and needs to be treated slightly differently from regular interstitials. [Learn more about prerolls](https://developers.google.com/ad-placement/apis#prerolls)

To place an interstitial ad, populate the following fields within the placement
config:

    adBreak({
       type: 'start',           // The type of this placement
       name: 'game_started',    // A descriptive name for this placement
       beforeAd: beforeAd,      // Prepare for the ad. Mute and pause the game flow
       afterAd: afterAd,        // Resume the game and un-mute the sound
       adBreakDone: breakDone,  // Always called (if provided) even if an ad didn't show
    });

The `type` argument is required, and we recommend that you **always name your
placements**. The other callbacks are optional.

### Call sequence

Review the call sequence for an interstitial ad.

![Interstitial ad call sequence diagram](https://developers.google.com/docs/images/interstitial-call-sequence.png)

#### Description

| Interstitial -- Detailed call sequence ||
| Your H5 Game | Ad Placement API |
|---|---|
|   | Initialization \& preloading of ads |
| Running the game |   |
| A good opportunity to show an ad... `adBreak()` → |   |
|   | There's an ad available and now is a good time to show it... ← `beforeAd()` |
| Game pauses, mutes the sound and gets ready to show the ad. `return` to the API → |   |
|   | The Ad Placement API renders the interstitial ad. The player can click the ad (which displays in a new tab). They must dismiss the ad in order to continue playing the game. |
|   | ←` afterAd()` is called if an ad has been shown |
| The game unpauses and unmutes the sound. |   |
|   | ←` adBreakDone()`adBreakDone() is always called (even if an ad wasn't shown) |
| The game logs analytics about this placement. |   |

#### Notes

- `adBreak()` is an asynchronous function that returns immediately.
- If there is no ad to display for a placement then none of the callbacks are called---that is, none of `beforeAd()`,`afterAd()`, are called.
- In order to ensure that your game doesn't continue to execute while the ad is showing, use the `beforeAd()` callback to mute the sound and pause the game.
- `beforeAd()` is synchronous, the Ad Placement API won't show an ad until it returns.
- Restart your game and un-mute the sound when you receive the `afterAd()` call.
- If provided, `adBreakDone()` is always called even if an ad wasn't shown in this placement.
- Calling `adBreak()` while another ad is showing will fail and a warning will be displayed on the JavaScript console.

## Prerolls

A preroll is an interstitial that displays before your game loads its UI. It's
the first thing a player sees when they navigate to your game. Because a preroll
happens very early in the page load, and your game isn't displayed yet---the
usual calls to pause and mute your game are not required. Instead you use the
`adBreakDone()` callback to sequence the start of your game with the
ad---that is, render the UI and start playing sound. Only one preroll can be
triggered for each page load.

### Call sequence

The call for a preroll is made very early in the page load. As your game has not
rendered its UI at this point, you should not pass the `beforeAd()` and
`afterAd()` callbacks. Instead, use the `adBreakDone()` callback to start your
game after the placement, as this is guaranteed to be called even if there was
no ad.

![Preroll ad call sequence diagram](https://developers.google.com/docs/images/preroll-call-sequence.png)

Calling the following code, early in your game logic will place a preroll ad.
Your UI should not be rendered before this code is called.

    // Game must not be running.
    // Nothing in the game area should be clickable
    adBreak({
       type: 'preroll',
       adBreakDone: startGame,
    })

| Preroll -- Detailed call sequence ||
| Your H5 Game | Ad Placement API |
|---|---|
|   | API initialization \& pre-caching of ads commences |
| Is running but has not started and has not displayed a UI |   |
| `adBreak(type:'preroll',...)` → |   |
|   | The Ad placement API finishes initializing and loading ads. If there is an ad it is shown. The player can click the ad (which displays in a new tab). They must dismiss it in order for the game to start. |
|   | ← `adBreakDone()` is always called (even if an ad wasn't shown) |
| The game UI is rendered to the screen and the player can now interact with it. The game can use the `placementInfo` object passed to `adBreakDone()` as needed (for example, to log additional analytics). |   |

#### Notes

- A preroll will always attempt to preload ads:
  - Calling `adConfig(preloadAds: 'on')` is not required with prerolls.
- Like other ad placements, a preroll may or may not show an ad.
- `beforeAd()` and `afterAd()` should not be passed to a preroll.
  - Because preroll ads run before your game starts, there's no need to pause or mute the game sound.
  - If you pass `beforeAd()` or `afterAd()` with a preroll, the call will fail and an error will be logged to the JavaScript console.
- A preroll automatically waits for the Ad Placement API to initialize and preload ads:
  - However, there's a timeout (2s) that prevents the call from delaying indefinitely. This ensures that `adBreakDone()` is called in a timely fashion and your game starts.
  - `adBreakDone()` is always called even if there's no ad.
- We recommend you use a preroll for placing ads before your game starts.
  - Alternatively, you can use the `onReady()` callback to `adConfig()` as a mechanism for sequencing your game logic with the initialization of the API and preloading ads.

## Rewarded ads

A rewarded ad allows you to reward your players with in-app items if they choose
to watch an ad. Whereas interstitials are *opt-out* , a player is shown the ad
and can choose to dismiss it. Rewarded ads are *opt-in*. A player chooses if and
when they would like to watch an ad in order to receive a reward.

Unlike interstitials, where the player can dismiss the ad at any time, in order
to receive a reward they must view the ad for a minimum amount of time (which
can vary depending on the ad creative being shown).

Because rewarded ads are optional for the player, they require deeper
integration into your game flow. You must provide functions to render a reward
prompt within your game, and to allocate the reward to the player if they watch
the ad.

Rewards must not have value outside of your app, they must not have (or be
easily exchanged for) monetary value, and must not be saleable or exchangeable
for goods and services, and you should not encourage players to click ads.
Please refer to the draft policy for interstitials and rewarded for more details.

Because rewards are optional for the player, you can add them anywhere that
makes sense within your game and can use them in addition to interstitials.
Like interstitials, these placements are *opportunities* to show rewarded ads.
The Ad Placement API will only call your code if a rewarded ad will *actually*
be offered at a particular point in your game.

Once again the goal here is to allow you to integrate your game with the Ad
Placement API once and then, over time using controls either in the tag, or in
AdSense, you can change the precise mix of ads that are activated--without having
to recode and re-release your game.

The type of a rewarded placement is always `'reward'` and all of the fields in
the placement config can be used.

    adBreak({
       type: 'reward',                      // The type of this placement
       name: '<name>',                      // A descriptive name for this placement
       beforeAd: () => {},                  // Prepare for the ad. Mute and pause the game flow
       afterAd: () => {},                   // Resume the game and re-enable sound
       beforeReward: (showAdFn) => {},      // Show reward prompt (call showAdFn() if clicked)
       adDismissed: () => {},               // Player dismissed the ad before it finished.
       adViewed: () => {},                  // Player watched the ad--give them the reward.
       adBreakDone: (placementInfo) => {},  // Always called (if provided) even if an ad didn't show
    });

The key new functions are `beforeReward()` which is the trigger that signals you
should render the reward prompt, and `adViewed()` which is called when the
player has successfully viewed the ad, so you can allocate their reward.

You might define a rewarded placement as follows:

    adBreak({
       type: 'reward',
       name: 'new_life_reward_1',
       beforeAd: pauseGame,
       afterAd: restartGame,
       beforeReward: showRewardPrompt,
       adDismissed: adDismissed,
       adViewed: adViewed,
       adBreakDone: breakDone,
    });

Rewarded ads start with a prompt in your game offering the player a reward if
they view an ad.

![Example ad prompt: Watch a video to get an extra life](https://developers.google.com/docs/images/rewarded-ad-description.png)

### Call sequence for a rewarded ad

![Rewarded call sequence diagram](https://developers.google.com/docs/images/rewarded-call-sequence.png)

#### Description

| Rewarded ad -- Detailed call sequence ||
| Your H5 Game | Ad Placement API |
|---|---|
|   | Initialization \& pre-caching of ads |
| Running the game |   |
| `adBreak(type:'reward', ... )` → |   |
|   | There is an ad available so start a rewarded ad placement. `beforeReward()` is called synchronously--immediately after the call to `adBreak()` ← `beforeReward(showAdFn)` |
| Game renders the reward prompt. This offers the player the opportunity to get a reward by watching an ad. More than one kind of reward could be offered (for example, a new life or a gold coin). The player can click a reward prompt, dismiss them, or simply ignore them. If they click a prompt, then the game stores the kind of reward they requested and calls `showAdFn()...` Otherwise if the reward prompt is dismissed or ignored then nothing will happen until you make another call to `adBreak()` with a reward placement type at which point the Ad Placement API will reset and clean up the state from this call. If the app calls `showAdFn` from a previous ad break it has no effect. |   |
| `showAdFn()` → |   |
|   | ← `beforeAd()` |
| Game pauses, mutes the sound and gets ready to show the ad `return` to the API → |   |
|   | The API shows the ad. It has a dismiss button and a countdown of how much time remains in the ad. |
| **IF the player dismisses the ad...** ||
|   | ← `adDismissed()` |
| Player dismissed the ad and the game does not issue the reward. |   |
| **ELSE** the player watches the ad to completion... ||
|   | ← `adViewed()` |
| Player watched the ad to completion and the game issues the reward. (This would typically be by setting some game state that is then picked up when the game restarts with the call to `afterAd()` below). |   |
| **After the ad has been watched or dismissed...** ||
|   | ← `afterAd()` is called if an ad has been shown |
| The game unpauses and unmutes the sound. |   |
|   | ←` adBreakDone()`adBreakDone() is always called (even if an ad wasn't shown) |
| The game logs analytics about this placement. |   |

#### Notes

- `adBreak()` is an asynchronous function that returns immediately.
- If there is no ad to display for a placement then none of the callbacks are called---that is, none of `beforeAd()`, `beforeReward()` are called.
- In order to ensure that your game doesn't continue to execute while the ad is showing, use the `beforeAd()` callback to mute the sound and pause the game.
- `beforeAd()` is synchronous, the Ad Placement API won't show an ad until it returns.
- Restart your game and un-mute the sound when you receive the `afterAd()` call.
- If provided, `adBreakDone()` is always called even if an ad wasn't shown in this placement.
- Calling `adBreak()` while another ad is showing will fail and a warning will be displayed on the JavaScript console.