Skip to contentGo to cookie choices
Skip to docs navigation
Engines

Phaser

Use the ZokoGames Phaser plugin or the JavaScript SDK in a Phaser game, with ad pausing, banners, saves, leaderboards and local testing.

About 17 minutes

https://docs.zokogames.com/engines/phaser

Phaser games run in the browser, so you have two ways in. Use the ZokoGames Phaser plugin (packages/sdk-engines/phaser), which pauses the game loop and the sound around ads for you, or call the JavaScript SDK directly. Both use the same calls, limits and error codes. Jargon such as "midgame" and "rewarded" is explained in the glossary.

Note

Status (1.7.1): run in a real browser against Phaser 3.90.0 and 4.2.1 (2026-11-23). Send the Phaser version and the exact error to support if the first import fails. The JavaScript SDK underneath is the tested part. Release 1.7.1 (script-load timeout) was re-run on 2026-11-23, in a browser and on production.

Install#

Download the Phaser plugin: /sdk-engines/zokogames-phaser-1.7.1.zip (the same files as the folder in the repository).

/sdk-engines/phaser.zip is always the latest version. Checksums: /sdk-engines/SHA256SUMS. Index of every engine package with its version, size and SHA-256: /sdk-engines/engines.json.

Pick the route that matches your game.

You have Do this
A finished Phaser game (JavaScript or TypeScript) Copy the plugin sources into your project and register the plugin (below), or skip the plugin and use the plain SDK.
A new game Start from the phaser starter kit. It already has the plugin under src/zoko/, four scenes and an npm run package script.

The plugin is plain TypeScript in packages/sdk-engines/phaser/src/: ZokoPlugin.ts, ZokoClient.ts, ZokoAdFlow.ts, ZokoLoadingBridge.ts, ZokoSceneMixin.ts, types.ts and an index.ts that re-exports them. Copy the folder (for example to src/zokogames-phaser/) and import from it. The starter kit holds the same files, formatted, in src/zoko/ and has no index.ts, so import ./zoko/ZokoPlugin there. The peer dependency is phaser ^3.80.0; the starter kit itself pins Phaser 4.2 and is type-checked and built against it.

You do not have to add a script tag: when window.ZokoGames is missing, the plugin injects https://sdk.zokogames.com/zokogames-sdk-v1.js itself (pass loadScript: false to turn that off). A script tag in index.html is still better, because the upload validator looks for the SDK URL (see build validation):

HTML
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>

A working game loop with the plugin#

This is one file that covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score. Every portal call is wrapped so the game also runs when the SDK is disabled (see local mode).

TypeScript
import Phaser from "phaser";
import { ZokoPlugin } from "./zokogames-phaser/ZokoPlugin";

// SDK calls must never break the game: swallow errors, return a fallback.
async function safe<T>(fn: () => Promise<T> | T, fallback: T): Promise<T> {
  try { return await fn(); } catch { return fallback; }
}

class Boot extends Phaser.Scene {
  constructor() { super("Boot"); }
  async create() {
    const z = this.zoko;                                   // available because of `mapping: "zoko"`
    await safe(() => z.ready(), null);                     // loads the script if missing, then SDK.init()
    const live = (() => { try { return z.sdk.environment !== "disabled"; } catch { return false; } })();
    this.registry.set("live", live);
    if (live) {
      await safe(() => z.sdk.game.loadingStart(), undefined);
      this.registry.set("best", Number(z.sdk.data.getItem("best") ?? "0") || 0);   // load: synchronous
      await safe(() => z.sdk.game.loadingStop(), undefined);
    }
    this.scene.start("Play");
  }
}

class Play extends Phaser.Scene {
  private score = 0;
  constructor() { super("Play"); }

  create() {
    const z = this.zoko;
    const live = this.registry.get("live") as boolean;
    const start = () => { if (live) void safe(() => z.sdk.game.gameplayStart(), undefined); };
    const stop = () => { if (live) void safe(() => z.sdk.game.gameplayStop(), undefined); };
    start();                                               // input is live now, not at page load
    this.game.events.on("hidden", stop);
    this.game.events.on("visible", start);
    this.events.once("shutdown", () => {
      this.game.events.off("hidden", stop);
      this.game.events.off("visible", start);
      stop();
    });
    // ... spawn targets, call this.finish() when the round ends
  }

  async finish() {
    const z = this.zoko;
    const live = this.registry.get("live") as boolean;
    if (!live) { this.scene.start("Play"); return; }
    await safe(() => z.sdk.game.gameplayStop(), undefined);

    // Save. Writes are batched and sent about a second later; reads are synchronous.
    if (this.score > (this.registry.get("best") as number)) {
      this.registry.set("best", this.score);
      try { z.sdk.data.setItem("best", String(this.score)); } catch { /* dataLimitExceeded */ }
    }
    // Leaderboard (needs a signed-in player and the board enabled in the console).
    await safe(async () => {
      const user = await z.sdk.user.getUser();
      if (!user) return;
      const encryptedScore = await encryptScore(this.score, BOARD_KEY, user.__dangerousUserId, GAME_ID);
      await z.sdk.user.submitScore({ encryptedScore, score: this.score });
    }, undefined);

    // Midgame ad at a natural break. Pauses sound and the loop from adStarted until adFinished OR adError.
    const { finished, error } = await z.requestAd("midgame");
    if (!finished) console.warn("no ad:", error?.code);   // adCooldown, unfilled, adblock ... the game just carries on
    this.scene.start("Play");
  }

  async watchForBonus() {                                   // call from a button press
    const { finished } = await this.zoko.requestAd("rewarded");
    if (finished) this.score += 10;                         // reward only after adFinished
  }
}

new Phaser.Game({
  type: Phaser.AUTO,
  parent: "game",
  scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, width: 1280, height: 720 },
  plugins: { global: [{ key: "ZokoPlugin", plugin: ZokoPlugin, start: true, mapping: "zoko", data: { syncMute: true } }] },
  scene: [Boot, Play],
});

encryptScore, BOARD_KEY and GAME_ID come from the leaderboards page, which has the AES-GCM helper and explains why a board without an encryption key accepts encryptedScore: "" with the plain score. Only signed-in players are ranked, and a submission that breaks a board rule is dropped silently while the call still resolves.

What the plugin gives you#

Member Behaviour (verified in ZokoPlugin.ts and ZokoAdFlow.ts)
ready() Loads the SDK script if window.ZokoGames is missing, then runs SDK.init(). Rejects with { code: "sdkNotLoaded" } when the script cannot load. Safe to call repeatedly. When the environment is not disabled it also registers settings and offline listeners and applies muteAudio to game.sound.mute (option syncMute, default true).
requestAd("midgame" | "rewarded") On adStarted it pauses all sound, mutes, and calls game.loop.sleep(). On adFinished, on adError, and when the request itself throws, it wakes the loop, restores mute (the portal's muteAudio or what it was before) and resumes sound. Resolves { finished, error? } and never rejects for ad problems.
version The JavaScript SDK release the plugin was written against (SDK_VERSION).
isAdPlaying true while an ad is on screen.
events Emits adStarted, adFinished, adError(error), settingsChange(settings) and offlineChange(offline).
sdk The raw SDK. Throws sdkNotInitialized before ready() resolved.
ad, banner, user, data, store, analytics, gameApi, environment, isQaTool, client The typed client. gameApi is the SDK game module (this.game is Phaser's own object). client is the underlying ZokoClient, which also has achievements (this.zoko.client.achievements.list(), unlock(key), onUnlock(cb); see achievements).
trackLoading(this.load) Reports a loader to the portal: loadingStart on start, loadingProgress (0 to 100) on progress, loadingStop on complete. Returns a function that detaches the listeners.
rectFromGameBounds(x, y, w, h) Converts a rectangle in game coordinates (the configured game width and height) to the normalised canvas rectangle the banner calls use.
requestBannerAt(id, x, y, w, h, size?) Positions a DOM container over a rectangle in game coordinates and requests a banner there; without size it requests the largest responsive size that fits.

The plugin file also exports runAdFlow, bindLoadingProgress, withZoko and ZOKO_SDK_SCRIPT_URL, and ZokoClient can be used on its own in unit tests (it needs no Phaser). this.zoko is also available through class X extends withZoko(Phaser.Scene) when the plugin key is ZokoPlugin.

Without the plugin#

If you do not want a plugin, call the SDK yourself. Initialise before you create the Phaser.Game, and write the ad helper so it resumes on both outcomes.

JavaScript
const SDK = window.ZokoGames?.SDK;
let live = false;

async function main() {
  if (SDK) { await SDK.init(); live = SDK.environment !== "disabled"; }   // init never rejects
  const game = new Phaser.Game({
    type: Phaser.AUTO,
    parent: "game",
    scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, width: 1280, height: 720 },
    scene: [Boot, Play],
  });
  if (live) {
    const apply = (s) => { game.sound.mute = s.muteAudio; };
    apply(SDK.game.settings);
    SDK.game.addSettingsChangeListener(apply);
  }
}

function showAd(game, type) {
  if (!live) return Promise.resolve(false);
  let paused = false;
  const pause = () => { if (paused) return; paused = true; game.sound.pauseAll(); game.sound.mute = true; game.loop.sleep(); };
  const resume = () => {
    if (!paused) return; paused = false;
    game.loop.wake();
    game.sound.mute = SDK.game.settings.muteAudio;
    game.sound.resumeAll();
  };
  return new Promise((done) => {
    SDK.ad.requestAd(type, {
      adStarted: pause,
      adFinished: () => { resume(); done(true); },
      adError: () => { resume(); done(false); },
    }).catch(() => { resume(); done(false); });          // throws (for example sdkDisabled) instead of calling adError
  });
}
main();

Pausing one scene with scene.pause() is not enough: tweens, timers on other scenes and the sound manager keep running. game.loop.sleep() stops the whole game step. requestAd resolves only after adFinished or adError has been delivered, so await showAd(...) is a safe place to resume game logic.

Kids mode. Since version 1.5.0 the wrapper exposes it: SDK.game.settings.kidsMode is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring disableChat, which the portal sets to true in the same cases. To test it, add ?kidsMode=true to the page address in local mode. See kids mode.

Banners#

Banner containers are DOM elements next to the canvas, not game objects. Request them on menu screens only and clear them before play.

HTML
<div id="game"></div>
<div id="menu-banner" style="width:728px;height:90px;margin:8px auto"></div>
JavaScript
SDK.banner.requestBanner({ id: "menu-banner", width: 728, height: 90 }).catch(() => {});
this.events.once("shutdown", () => SDK.banner.clearAllBanners());

With the plugin, await this.zoko.requestBannerAt("hud", 20, 20, 300, 250, "300x250") creates the container for you over that rectangle of the canvas. Banners are refused while a video ad plays (videoAdPlaying) and a container can refresh only every 30 seconds (bannerCooldown).

Room data channel#

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after updateRoom (or after joining from an invite) and ends with leftRoom, needs a signed-in player and a portal with realtime enabled (otherwise roomUnavailable), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of A-Z a-z 0-9 _ . : -. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (notInRoom, notHost, payloadTooLarge, stateTooLarge, unknownMember, rateLimited, roomUnavailable) are in the game module and the multiplayer guide.

The plugin has no room helpers of its own; use the SDK's game.room through this.zoko.gameApi.room. It is undefined on an SDK older than 1.3.0, so check it first. Methods: send(data, { to }), setState(patch), getState(), members(), isHost(), selfId, and onMessage, onState, onMembers, onHostChange, onError, each returning an unsubscribe function. On localhost the SDK's local mode makes two browser tabs in the same room id behave like two players.

TypeScript
async startMatch() {
  await this.zoko.ready();
  await this.zoko.gameApi.updateRoom({ roomId: "match-1", isJoinable: true });
  const room = this.zoko.gameApi.room;
  if (!room) return;
  room.onMessage((m) => this.placeMark((m.data as { cell: number }).cell));
  room.onHostChange((_hostId, isHost) => { if (isHost) void room.setState({ turn: "X" }); });
}

onCellClicked(cell: number) { void this.zoko.gameApi.room?.send({ cell, mark: "X" }); }

Purchases#

TypeScript
const store = this.zoko.sdk.store;
if (store.isAvailable) {
  try {
    const items = await store.getCatalogItems({ limit: 20 });
    await store.buyItem(items[0].sku);
    const token = await store.getPurchaseToken();            // send to your server and verify there
  } catch (e) {
    if ((e as { code?: string }).code === "purchaseCancelled") return;
  }
}

Check isAvailable before showing any purchase UI and verify ownership on your server. See in-game purchases. On localhost the SDK's local mode serves a test store.

Export settings that matter on the web#

  • Bundle with relative paths. Vite: base: "./". Root-absolute paths (starting with a slash) break under the game's own origin and raise the absolute_path warning. See technical requirements.
  • Do not pre-compress. Phaser, unlike Unity, asks for plain file names. A file ending in .br or .gz is served with Content-Encoding, but your page would still request the plain name, so ship plain files. The game origin does serve a .br or .gz suffix with the matching Content-Encoding and caches game files for a year under the build id. Whether plain files are compressed in transit is not documented or guaranteed by the portal, and the initial-download estimate uses uncompressed sizes, so keep the files small.
  • Size. Pack textures into atlases and keep audio at modest bitrates. Load later levels after the first scene instead of in preload. The upload limits are 1,500 files, 250 MB unpacked and about 50 MB initial download (20 MB for mobile); see first frame fast.
  • Canvas sizing. The frame size changes with fullscreen and rotation. Phaser.Scale.FIT with autoCenter: CENTER_BOTH keeps the game legible at every required resolution. The starter kit uses 800 by 450.
  • Audio unlock. Browsers block sound until the first pointer or key event. Phaser's sound manager handles the unlock itself; start music from a button press or after the sound manager's unlocked event, not unconditionally in create(). Ads and syncMute do not replace this.
  • Fullscreen. Prefer the fullscreen button in the portal's frame bar: it fullscreens the whole frame, including the portal's controls. The frame carries allow="fullscreen", so this.scale.startFullscreen() is permitted, but it fullscreens only your canvas; do not add a competing button.
  • Memory. There is no threading or SharedArrayBuffer in the portal frame (the portal does not send cross-origin isolation headers), which Phaser does not need.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

Chat reports, screenshots and storage mirror#

Since SDK 1.4.0: zoko.gameApi.reportChat(report), zoko.gameApi.onScreenshotRequest(handler) and zoko.data.mirrorLocalStorage({ prefix: "save_" }). ready() registers a default screenshot provider built on renderer.snapshot; pass screenshots: false to the plugin config to skip it. The mirror only covers localStorage. The simulator accepts all three.

Test locally#

Phaser always runs in a browser, so there is no editor simulator. Serve the game from localhost (the starter kit does it with npm run dev, port 5173) and the SDK starts in its own local mode: a three-second overlay stands in for each ad, banners are dashed boxes, two fake players exist, and cloud saves go to localStorage. Two things trip people up:

  • A second midgame request within three minutes of the last ad fails with adCooldown. That is the real rule, so your game must handle it.
  • submitScore is accepted and does nothing visible in local mode, and the local token is unsigned.

Add ?sdk_debug=true to log every call, ?ad_response=unfilled to force ad failure, and ?user_response=logged_out to test the guest path. Then open the Preview tool, enter your local address and watch the requirements checklist tick.

API#

init#

JavaScript Phaser
init await this.zoko.ready()
environment this.zoko.environment
isQaTool this.zoko.isQaTool
JavaScript Phaser
ad.requestAd this.zoko.requestAd(type) (pausing) or this.zoko.ad.requestAd(type, callbacks)
ad.requestAd.adStarted callbacks.adStarted of this.zoko.ad.requestAd(type, callbacks); this.zoko.requestAd(type) pauses for you
ad.requestAd.adFinished callbacks.adFinished; requestAd resolves { finished: true }
ad.requestAd.adError callbacks.adError(error); requestAd resolves { finished: false, error }
ad.hasAdblock this.zoko.ad.hasAdblock()
JavaScript Phaser
banner.requestBanner this.zoko.banner.requestBanner({ id, width, height })
banner.requestResponsiveBanner this.zoko.banner.requestResponsiveBanner()
banner.clearBanner this.zoko.banner.clearBanner()
banner.clearAllBanners this.zoko.banner.clearAllBanners()

game.*#

JavaScript Phaser
game.settings this.zoko.gameApi.settings
game.addSettingsChangeListener this.zoko.gameApi.addSettingsChangeListener(fn) / this.zoko.events.on("settingsChange", fn)
game.removeSettingsChangeListener this.zoko.gameApi.removeSettingsChangeListener()
game.gameplayStart this.zoko.gameApi.gameplayStart()
game.gameplayStop this.zoko.gameApi.gameplayStop()
game.loadingStart this.zoko.gameApi.loadingStart()
game.loadingStop this.zoko.gameApi.loadingStop()
game.loadingProgress this.zoko.gameApi.loadingProgress(percentage)
game.happytime this.zoko.gameApi.happytime()
game.reportGameCompletedPercentage this.zoko.gameApi.reportGameCompletedPercentage()
game.reportChat zoko.gameApi.reportChat(report)
game.onScreenshotRequest zoko.gameApi.onScreenshotRequest(handler) / zoko.useDefaultScreenshot()
game.setGameContext this.zoko.gameApi.setGameContext()
game.clearGameContext this.zoko.gameApi.clearGameContext()
game.isInstantMultiplayer this.zoko.gameApi.isInstantMultiplayer
game.isInstantJoin this.zoko.gameApi.isInstantJoin
game.isOffline this.zoko.gameApi.isOffline
game.addOfflineListener this.zoko.gameApi.addOfflineListener(fn) / this.zoko.events.on("offlineChange", fn)
game.removeOfflineListener this.zoko.gameApi.removeOfflineListener(fn)
game.updateRoom this.zoko.gameApi.updateRoom()
game.leftRoom this.zoko.gameApi.leftRoom()
game.addJoinRoomListener this.zoko.gameApi.addJoinRoomListener()
game.removeJoinRoomListener this.zoko.gameApi.removeJoinRoomListener()
game.inviteParams this.zoko.gameApi.inviteParams
game.inviteLink this.zoko.gameApi.inviteLink()
game.getInviteParam this.zoko.gameApi.getInviteParam()
game.showInviteButton this.zoko.gameApi.showInviteButton(params)
game.hideInviteButton this.zoko.gameApi.hideInviteButton()
game.room this.zoko.gameApi.room
game.room.send this.zoko.gameApi.room.send(data, { to })
game.room.onMessage this.zoko.gameApi.room.onMessage(cb)
game.room.addMessageListener this.zoko.gameApi.room.addMessageListener(cb)
game.room.removeMessageListener this.zoko.gameApi.room.removeMessageListener(cb)
game.room.setState this.zoko.gameApi.room.setState(patch)
game.room.getState this.zoko.gameApi.room.getState()
game.room.onState this.zoko.gameApi.room.onState(cb)
game.room.addStateListener this.zoko.gameApi.room.addStateListener(cb)
game.room.removeStateListener this.zoko.gameApi.room.removeStateListener(cb)
game.room.members this.zoko.gameApi.room.members()
game.room.onMembers this.zoko.gameApi.room.onMembers(cb)
game.room.addMembersListener this.zoko.gameApi.room.addMembersListener(cb)
game.room.removeMembersListener this.zoko.gameApi.room.removeMembersListener(cb)
game.room.isHost this.zoko.gameApi.room.isHost()
game.room.onHostChange this.zoko.gameApi.room.onHostChange(cb)
game.room.addHostChangeListener this.zoko.gameApi.room.addHostChangeListener(cb)
game.room.removeHostChangeListener this.zoko.gameApi.room.removeHostChangeListener(cb)
game.room.selfId this.zoko.gameApi.room.selfId
game.room.onError this.zoko.gameApi.room.onError(cb)
game.room.addLeftListener this.zoko.gameApi.room.addLeftListener(cb)
game.room.removeLeftListener this.zoko.gameApi.room.removeLeftListener(cb)
game.room.addErrorListener this.zoko.gameApi.room.addErrorListener(cb)
game.room.removeErrorListener this.zoko.gameApi.room.removeErrorListener(cb)

user.*#

JavaScript Phaser
user.isUserAccountAvailable this.zoko.user.isUserAccountAvailable
user.systemInfo this.zoko.user.systemInfo
user.getUser this.zoko.user.getUser()
user.listFriends this.zoko.user.listFriends()
user.getUserToken this.zoko.user.getUserToken()
user.showAuthPrompt this.zoko.user.showAuthPrompt()
user.addAuthListener this.zoko.user.addAuthListener()
user.removeAuthListener this.zoko.user.removeAuthListener()
user.showAccountLinkPrompt this.zoko.user.showAccountLinkPrompt()
user.submitScore this.zoko.user.submitScore()
user.getXsollaUserToken this.zoko.user.getXsollaUserToken()

data.*#

JavaScript Phaser
data.getItem this.zoko.data.getItem(key)
data.setItem this.zoko.data.setItem(key, value)
data.removeItem this.zoko.data.removeItem()
data.clear this.zoko.data.clear()
data.mirrorLocalStorage zoko.data.mirrorLocalStorage(options)

store.*#

JavaScript Phaser
store.isAvailable this.zoko.store.isAvailable
store.getCatalogItems this.zoko.store.getCatalogItems({ limit, offset })
store.getPlayerInventory this.zoko.store.getPlayerInventory({ limit, offset })
store.buyItem this.zoko.store.buyItem(itemId)
store.consumeItem this.zoko.store.consumeItem()
store.getPurchaseToken this.zoko.store.getPurchaseToken()
store.setSandbox this.zoko.store.setSandbox()

achievements.*#

JavaScript Phaser
achievements.list this.zoko.achievements.list()
achievements.unlock this.zoko.achievements.unlock(key)
achievements.onUnlock this.zoko.achievements.onUnlock(fn)

analytics.*#

JavaScript Phaser
analytics.trackOrder this.zoko.analytics.trackOrder()
analytics.track this.zoko.analytics.track(name, params)

constants#

JavaScript Phaser
ERROR_CODES ZOKO_ERROR_CODES.<module>
SDK_VERSION this.zoko.version

Known pitfalls#

  • trackLoading before ready(). The plugin's loading bridge calls the SDK from the loader's start event. If ready() has not resolved by then, that call fails with sdkNotInitialized (a rejected promise; it no longer throws inside the event handler) and the loading is not reported. Call await this.zoko.ready() in a boot scene first, then call trackLoading(this.load) in the init() of the next scene that loads assets.
  • sdkNotLoaded. The script was blocked or offline and loadScript is off or failed. Your game should still start; the starter kit shows the pattern.
  • Calls on a disabled SDK throw sdkDisabled. Check sdk.environment !== "disabled" first, as above, or an unhandled rejection reaches your console.
  • Sound stays muted after an ad. Something else changed sound.mute during the ad. The plugin restores the portal's muteAudio value, or the value it saw at adStarted.
  • this.zoko is undefined. Register the plugin with mapping: "zoko", or extend withZoko(Phaser.Scene) and keep the key ZokoPlugin.
  • Banner in the wrong place. requestBannerAt converts game coordinates using the configured game size; check your Scale Manager mode.
  • Reward granted twice. Grant on finished === true only, never on the button press.

Next#