# Video ads

**Purpose:** `SDK.ad` asks the portal to show a full-screen video ad and tells your game when it starts, finishes or fails, so you can pause and resume. Two types exist:

- **midgame**: shown at a natural break, such as between levels.
- **rewarded**: the player opts in and receives something when it finishes.

Today the portal fills both with its own house ads, because no ad network is connected yet, so ads earn no revenue for now (see [feature status](https://docs.zokogames.com/business/faq#feature-status)). Your integration works the same either way.

Ads are served for games in **full launch** whose developer has enabled ads, and never for kids' games. In basic launch, in a reviewer's QA frame and anywhere else ads are off, `requestAd` fails with `adsDisabled`; build your integration as if that can always happen. The Preview tool runs your build with ads switched on, so you can test the real ad flow before full launch. Only ads requested through the SDK are allowed. Read the [advertisement rules](https://docs.zokogames.com/requirements/advertisements) before you design placements, and the [monetisation guide](https://docs.zokogames.com/guides/ad-monetisation) for pacing.

## At a glance

Every member of `SDK.ad`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `requestAd(type: "midgame" \| "rewarded", callbacks?: AdCallbacks): Promise<void>` | Nothing, after `adFinished` or `adError` has run. | The promise rejects only with `invalidArgument`, `sdkNotInitialized` or `sdkDisabled`. Every ad failure goes to `adError`: `adsDisabled`, `unfilled`, `adblock`, `adCooldown`, `other`, `timeout`. | 1.0.0 |
| `hasAdblock(): Promise<boolean>` | `true` when a blocker is detected, otherwise `false`. | `sdkNotInitialized`, `sdkDisabled`, `timeout`. | 1.0.0 |

The type `AdCallbacks` (`adStarted`, `adFinished`, `adError`, all optional) and the type `AdType` are in the declaration file, see the declaration file described in the SDK introduction.

## Lifecycle

```text
requestAd(type, callbacks)
  -> (portal checks: ads on? connection? cooldown? gameplay started? ad blocker?)
       refused  -> adError(code)                           game keeps running, nothing to resume
       accepted -> adStarted   pause game + mute audio
                   -> adFinished | adError   resume game + audio -> gameplayStart()
  -> the promise resolves after adFinished or adError has run
```

Call `SDK.game.gameplayStop()` before you request an ad and `gameplayStart()` after it, so playtime is not counted while the ad is on screen.

## requestAd

```ts
requestAd(type: "midgame" | "rewarded", callbacks?: AdCallbacks): Promise<void>

interface AdCallbacks {
  adStarted?: () => void;
  adFinished?: () => void;
  adError?: (error: SdkError) => void;
}
```

The returned promise resolves **after** `adFinished` or `adError` has been called, never before. Exactly one of the two fires per request, and all three callbacks are optional. `adStarted` fires only when the ad really starts, so an ad refused up front calls only `adError`. After `adStarted`, `adFinished` or `adError` is always delivered when the ad ends (the player finishes or closes it, or the portal reports a failure), but nothing bounds how long that takes: the only limit in the SDK is the 30 seconds before the ad starts, so do not add a game-side timer that resumes play while the ad is still on screen. Once the ad has started there is no time limit, because the player may keep it open as long as they like; but if the portal neither answers nor starts the ad within 30 seconds, `adError` is called with `timeout`. It rejects (instead of calling `adError`) only for `invalidArgument` (the type is not exactly `"midgame"` or `"rewarded"`) and for `sdkNotInitialized` or `sdkDisabled`.

:::tabs
== Midgame
<!-- docs-sample: uses game, audio -->
```js
async function showMidgame() {
  await SDK.ad.requestAd("midgame", {
    adStarted: () => { game.pause(); audio.mute(); },
    adFinished: () => { audio.unmute(); game.resume(); },
    adError: (err) => { console.warn(err.code); audio.unmute(); game.resume(); },
  });
}
```
== Rewarded
<!-- docs-sample: uses rewardButton, game, audio, grantExtraLife, showMessage -->
```js
rewardButton.addEventListener("click", async () => {
  let earned = false;
  await SDK.ad.requestAd("rewarded", {
    adStarted: () => { game.pause(); audio.mute(); },
    adFinished: () => { earned = true; },
    adError: () => { earned = false; },
  });
  audio.unmute();
  game.resume();
  if (earned) grantExtraLife();
  else showMessage("No ad is available right now, try again later.");
});
```
:::

### Rules for callbacks

- **Pause and mute inside `adStarted`**, not when you call `requestAd`. The request may fail or take a moment; the player should not see a frozen game before the ad exists.
- **Resume in both `adFinished` and `adError`.** A game stuck paused after a failed ad is the most common reason for a failed QA.
- **Never give a reward in `adError`.** If the player closes a rewarded ad early, it ends with `adError`, so no reward is due; a skipped midgame ad counts as finished.
- Callbacks are wrapped, so an exception inside one does not break the SDK.

### One ad at a time

While a request is in progress a second `requestAd` does not start another ad; its `adError` callback receives `{ code: "other" }` and its promise resolves at once, while the first request carries on. Disable your trigger button while waiting.

**Arguments and ordering.** `callbacks` is an object, `null` or omitted: since SDK 1.6.1 `null` counts as no callbacks (on 1.6.0 and earlier, pass nothing rather than `null`). Since SDK 1.6.3 the console shows one warning per page (`[ZokoGames SDK] ad.requestAd: ... Pass { adStarted, adFinished, adError } as functions`) when the object cannot work: a bare function instead of an object, a misspelled name such as `onFinished`, or a value that is not a function. `undefined`, `null` and `{}` stay silent, and the call behaves exactly as before, so a misspelled callback is simply never called. If the object cannot be read at all (a revoked `Proxy`, a getter that throws), the request still settles and the promise resolves; on 1.6.2 and earlier it stayed pending for ever. Once `init()` has resolved, the type is checked first: `requestAd("banner")` rejects with `invalidArgument` (the message says what it got, such as `got "banner"`; compare the `code`, not the text), and so does `requestAd()`. Call `requestAd` only after `await SDK.init()`, otherwise it rejects with `sdkNotInitialized`; with the environment `"disabled"` it rejects with `sdkDisabled`, so check `SDK.environment` and skip the ad. The callbacks run in this order only: `adStarted` (when the ad appears), then `adFinished` or `adError`. A request that fails before the ad appears calls only `adError`, and the promise then resolves. If the portal answers neither way within 30 seconds, `adError` gets `timeout` and the game must resume as for any other error. Do not call `requestAd` while the game is mid-play: call `gameplayStop()` first, and `gameplayStart()` once the ad is over (the Preview tool flags a request made while playing).

## Ad-free members

A player with an ad-free membership or pass sees no midgame ads and no banners. For them `requestAd("midgame")` does not fail: `adStarted` and then `adFinished` fire at once with nothing on screen, so your resume code runs exactly as after a real ad. Rewarded ads still play, because the player asks for them. Banner requests fail with `bannersDisabled`. Never rely on an ad having been seen to unlock something for a midgame request.

## Error codes

| Code | Meaning | What to do |
| --- | --- | --- |
| `adsDisabled` | Ads are off for this game: basic launch, a kids' game, ads not enabled, the ad provider switched off, that ad type switched off by the portal, or the game runs inside a store app build. Inside the portal's Android app no ad is shown before the game either. | Continue without an ad, give no reward unless your design allows an alternative. |
| `unfilled` | The portal started no ad: nothing was available, or the player is offline. | Continue; try again later. |
| `adblock` | The portal detected an ad blocker and started no ad. `hasAdblock()` lets you check in advance. | Continue; see below. |
| `adCooldown` | A midgame ad was requested within the cooldown (three minutes by default) of the previous ad of either type, the portal's per-session or per-day ad limit was reached, or the game has not called `gameplayStart()` yet (see [Gameplay first](#gameplay-first)). | Continue; the break was too early. In the last case the message reads "Midgame ads are available after gameplay starts: call game.gameplayStart() first"; call `gameplayStart()` when play begins. |
| `other` | Anything else: a request already in progress, a rewarded ad the player closed early, or a failure inside the ad. | Continue. |

For a rewarded request the `adblock` error is also returned when the ad provider's script fails to load or times out on this page (a midgame request plays the portal's own ad instead). No reward is granted in that case.

When the player is a guest the codes are the same; ads do not depend on an account.

An invalid `type` argument rejects with `invalidArgument`, and a call before `init()` has resolved (or with the SDK disabled) rejects with `sdkNotInitialized` or `sdkDisabled`; none of these call `adError`.

## Cooldown

Midgame ads are limited to one every **180 seconds** by default (the portal can set a different value per game). The timer starts whenever any ad starts, so a midgame request right after a rewarded ad is declined with `adCooldown`. Request midgame ads at natural breaks and let the portal decline when it is too soon; do not build your own timer around exactly three minutes. Rewarded ads are player-initiated and are never declined for cooldown. The portal's optional per-session and per-day ad limits also apply to midgame ads only.

## Gameplay first {#gameplay-first}

A midgame ad is refused until your game has called `SDK.game.gameplayStart()` at least once in that game window. The refusal uses the code `adCooldown`, with its own message: "Midgame ads are available after gameplay starts: call game.gameplayStart() first". No ad starts and `adStarted` never runs, so only `adError` is called. Compare the `code`, not the message.

Call `gameplayStart()` when the player starts to play, before your first ad break. A game that never calls it still gets midgame ads: the portal allows them 30 seconds after play begins, counted from the moment the ad before the game has ended or been skipped. Reloading the game starts the wait again. Rewarded ads are not affected.

Since SDK 1.6.4 local mode applies the same rule: a midgame request before `gameplayStart()` fails with `adCooldown` and the same message, and a game that never calls it gets midgame ads after 30 seconds of visible page time. Rewarded ads are not gated. SDK 1.6.3 and earlier played the ad in local mode. The site and the [Preview tool](https://www.zokogames.com/preview) show the refusal as before.

## hasAdblock

```ts
hasAdblock(): Promise<boolean>
```

Resolves `true` when an adblocker is detected. It never rejects for a blocker, only for `sdkNotInitialized`, `sdkDisabled` or `timeout`. In a kids' game it resolves `false`, because no network ad code runs there.

<!-- docs-sample: uses rewardButton, showAlternativeReward -->
```js
if (await SDK.ad.hasAdblock()) {
  rewardButton.title = "Rewarded ads are unavailable while an ad blocker is active.";
  showAlternativeReward();
}
```

Players with an adblocker must be able to play the whole game. You may disable features that depend on rewarded ads, with a short notice, and must offer another way to get the same reward. Do not show pop-ups asking players to turn the blocker off.

## In local mode

In local mode an ad is a 3-second overlay; in the portal it is an ad screen with a countdown. Either way, the callbacks run in the same order. `adStarted` fires when it appears and `adFinished` when it closes. Use it to check your pause, mute and resume paths, then repeat in the [Preview tool](https://www.zokogames.com/preview), where real ad plumbing and failures occur.

| Situation in local mode | Result |
| --- | --- |
| Normal request | Overlay for 3 seconds, `adStarted`, `adFinished`. Rewarded ads cannot be closed early, so `adError` never follows a rewarded ad. |
| Second midgame request inside the cooldown | `adError` with `adCooldown`. |
| Midgame request before `gameplayStart()` | `adError` with `adCooldown` and the message "Midgame ads are available after gameplay starts: call game.gameplayStart() first", until `gameplayStart()` has been called or 30 seconds of visible page time have passed (SDK 1.6.4; earlier versions played the ad). Rewarded requests are not gated. See [Gameplay first](#gameplay-first). |
| Request while the overlay is up | `adError` with `other`. |
| `?ad_response=adsDisabled`, `unfilled`, `adblock` or `other` | The request fails with that code in `adError`. `ad_response=adblock` also makes `hasAdblock()` resolve `true`. |
| Offline, ad-free, kids | Not simulated; use the [Preview tool](https://www.zokogames.com/preview). |

Local mode also applies the midgame cooldown (180 seconds, counted from any ad); rewarded requests are never held back by it. A forced `ad_response` is checked before the cooldown. A misspelled value (`?ad_response=adblocked`) is ignored, so the ad plays normally; since SDK 1.6.3 the console prints one warning per page that names the switch and the accepted values.

**Common mistakes.** What the Preview checklist and QA reviewers flag most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| The game is paused or muted when `requestAd` is called | A frozen, silent game when the request fails or is refused | Pause and mute inside `adStarted` only. |
| Only `adFinished` resumes the game | The game stays paused after `adError` (a refused, blocked or timed-out ad) | Resume in both callbacks, or after the awaited promise. |
| A reward is granted in `adStarted` or `adError`, or after the await without a flag | Players are rewarded for an ad that failed or was closed early | Set a flag in `adFinished` only and grant the reward when it is set. |
| `requestAd` is called while `gameplayStart` is active | The Preview checklist item "ad breaks stop gameplay" fails, and playtime counts the ad | Call `gameplayStop()` before the request and `gameplayStart()` after it. |
| `gameplayStart()` is never called after an ad | The Preview checklist item "resume after an ad" warns | Call it in the resume path. |
| A midgame ad is requested before the game has called `gameplayStart()` | `adCooldown` with the message "Midgame ads are available after gameplay starts", and no ad | Call `gameplayStart()` when play begins, before the first break. Local mode shows it too since SDK 1.6.4. |
| A midgame ad is requested every few seconds or on a timer of your own | `adCooldown` for most requests | Ask only at natural breaks and treat `adCooldown` as "no ad now". |
| The reward button stays enabled while an ad is loading | A second request gets `adError` with `other` | Disable the button until the promise resolves. |
| A rewarded ad is required to progress | Players with a blocker, an offline player or an ad-free member are stuck | Check `hasAdblock()` and offer another way to get the same reward. |
| A rewarded ad is offered when `requestAd` is not possible (disabled SDK) | A rejected promise with `sdkDisabled` | Check `SDK.environment` first and wrap the call in `try`/`catch`. |

## Putting it together

<!-- docs-sample: uses game, audio -->
```js
async function onLevelComplete() {
  await SDK.game.gameplayStop();
  await SDK.ad.requestAd("midgame", {
    adStarted: () => { game.pause(); audio.mute(); },
    adFinished: () => { audio.unmute(); },
    adError: () => { audio.unmute(); },
  });
  game.resume();
  await SDK.game.gameplayStart();
}
```

## Next steps

- [Banners](https://docs.zokogames.com/sdk/banners)
- [Audio, pausing and ads](https://docs.zokogames.com/guides/audio-and-ads)
- [Advertisement rules](https://docs.zokogames.com/requirements/advertisements)
