Skip to content
Docs pages

Developers · Advanced and FAQ

Bridge protocol

The low-level postMessage protocol between a game and the portal, for when you can't use the SDK file — envelope, requests, events, origin checks, timeouts and error codes.

On this page

The SDK file is itself a client of this protocol. Use the SDK if you can: it validates arguments, batches events and storage writes, falls back to standalone on its own, and de-duplicates pause/resume. Only implement the protocol yourself when your environment can't load the SDK file (for example a runtime that manages its own event loop) or when you are writing a client for another language.

Detecting the portal

The portal opens your game at index.html?wsg=1&host=<portal origin>&lang=<vi|en>&v=<version> (plus wsg_test=1 in test mode). Talk to the portal only when all three conditions hold:

  1. You are inside an iframe: window.parent !== window.
  2. The wsg query parameter equals 1.
  3. The host query parameter is a valid http or https origin.

Then send an init request. With no answer within 3 seconds, assume there is no portal and run your own standalone mode.

Envelope

TypeScript
interface BridgeMessage {
  wsg: 1; // protocol version
  kind: 'req' | 'res' | 'evt';
  id?: string; // required for req and res
  type: string; // request or event name
  payload?: unknown;
  error?: { code: string; message: string }; // only in failed res
}
  • Game → portal: kind: 'req', with a unique id per request (for example r1, r2), sent with window.parent.postMessage(msg, host).
  • Portal → game: kind: 'res' with the same id and type as the request; on success it carries a payload (always an object, {} when there is nothing), on failure an error. The portal also sends kind: 'evt' messages on its own.
  • Messages with the wrong shape (wsg other than 1, missing kind or type) are silently ignored on both sides.
  • payload goes through postMessage's structured clone: round-trip your data through JSON before sending to avoid DataCloneError on functions or special objects.

Origin checks

  • The game only accepts messages where event.source === window.parent and event.origin === host.
  • The portal only accepts messages from the game iframe's own contentWindow with event.origin equal to https://games.leonogames.com, and only sends to that origin.
  • Never use '*' as the targetOrigin: always pass host.

Timeouts

RequestTimeoutWhen it expires
init3 secondsRun standalone
ads.interstitial, ads.rewarded120 secondsTreat as { shown: false, reason: 'error' }
Everything else10 secondsA timeout error

Requests from the game

typepayloadReturned payloadWhat the portal checks
init{ gameId, sdkVersion?, gameVersion? }InitContext or { disabled: true }gameId is a 1–1024 character string (use the slug)
loading.start—{}
loading.progress{ percent }{}percent from 0 to 100
loading.finished—{}Removes the loading overlay
gameplay.start—{}
gameplay.stop—{}
happy{ intensity? }{}intensity from 0 to 1
track{ events: [{ name, props?, ts? }] }{ accepted }At most 100 events per request; name matches ^[a-z][a-z0-9_]{1,63}$; ts is epoch ms; events whose props exceed 2 KB are dropped and not counted in accepted
ads.interstitial{ placement? }AdResultplacement at most 64 characters
ads.rewarded{ placement? }AdResultSame as above
lb.submit{ score, meta? }SubmitResultscore is a number; scoring rules run on the server
lb.top{ period?, limit? }{ entries }Defaults all and 10; limit an integer 1–100
lb.around{ period?, radius? }{ entries }radius an integer 0–10, default 5
lb.me{ period? }{ entry }entry may be null
lb.show{ period? }{}
storage.get{ key }{ value }key 1–128 characters; value is null when missing
storage.set{ entries }{}Merged into the existing data, a null value deletes the key; each request is one write (at most 30 per minute)
storage.remove{ key }{}
storage.getAll—{ data }
share{ text?, score?, url? }{ ok }text at most 280 characters; url an absolute http/https URL
player.token—{ token }token is a JWT or null
player.login—{ player }

The InitContext, AdResult, SubmitResult and LeaderboardEntry types are exactly those of the SDK reference; InitContext.entryParams is the filtered query of your game's page on the portal (see getEntryParams()) and doesn't include the iframe URL's query. A request with an unknown type or an invalid payload gets an invalid_argument error.

Events from the portal

typepayloadWhen
pause—The tab is hidden (except while an ad is showing); before an ad appears; the portal opens the leaderboard (lb.show)
resume—The tab is visible again; after an ad closes; the player closes the leaderboard. Only sent when no other reason to stay paused remains
audio{ enabled }false before an ad, true after it
visibility{ visible }The portal page's visibility changes
authchange{ player }The player info changed

A hand-written client should ignore pause while already paused and resume while already running, as the SDK does. If an ad ends while the tab is still hidden or the leaderboard is open, the portal sends audio(true) but no resume, then sends pause again right after the ad's res (for clients that resume on their own when they get the result, like the SDK).

Error codes

error.code is one of not_initialized, timeout, quota_exceeded, invalid_argument, rate_limited, unavailable, internal. The portal returns:

  • invalid_argument: an unknown type, an invalid payload, or data rejected by the API;
  • not_initialized: the play session has ended (for lb.submit, player.login);
  • quota_exceeded: storage went over 100 KB;
  • rate_limited: an API rate limit was hit;
  • unavailable: the portal couldn't reach its API (network down, access denied), or a portal admin turned that API off for the game (lb.* when the leaderboard is off, storage.* when cloud save is off; turned-off ads answer { shown: false, reason: 'disabled' } and turned-off sharing answers { ok: false });
  • internal: anything else.

Standard sequence

One round
game → req init                  portal ← creates or reuses the play session, res InitContext
game → req loading.start … loading.progress … loading.finished
game → req gameplay.start        portal: records the first play, awards XP
game → req track {…}
game → req gameplay.stop         (game over)
game → req lb.submit {score}     portal → API → res SubmitResult
game → req ads.interstitial      portal → evt pause, evt audio(false) → ad → evt audio(true), evt resume → res AdResult
game → req gameplay.start        (new round)

A minimal client

JavaScriptbridge-client.js
const params = new URLSearchParams(location.search);
const host = params.get('wsg') === '1' ? params.get('host') : null;
const pending = new Map();
const listeners = {};
let seq = 0;

window.addEventListener('message', (event) => {
  if (!host || event.source !== window.parent || event.origin !== host) return;
  const msg = event.data;
  if (!msg || msg.wsg !== 1) return;
  if (msg.kind === 'res') {
    const p = pending.get(msg.id);
    if (!p) return;
    pending.delete(msg.id);
    clearTimeout(p.timer);
    if (msg.error) p.reject(msg.error);
    else p.resolve(msg.payload);
  } else if (msg.kind === 'evt') {
    for (const cb of listeners[msg.type] || []) cb(msg.payload);
  }
});

function request(type, payload) {
  return new Promise((resolve, reject) => {
    const id = `r${++seq}`;
    const ms = type === 'init' ? 3000 : type.startsWith('ads.') ? 120000 : 10000;
    const timer = setTimeout(() => {
      pending.delete(id);
      reject({ code: 'timeout', message: type });
    }, ms);
    pending.set(id, { resolve, reject, timer });
    window.parent.postMessage({ wsg: 1, kind: 'req', id, type, payload }, host);
  });
}

function on(type, cb) {
  (listeners[type] = listeners[type] || []).push(cb);
}

async function connect(gameId) {
  if (!host || window.parent === window) return { environment: 'standalone' };
  try {
    const ctx = await request('init', { gameId });
    return ctx.disabled ? { environment: 'disabled' } : ctx;
  } catch {
    return { environment: 'standalone' }; // the portal didn't answer within 3 seconds
  }
}

async function main() {
  const ctx = await connect('my-game');
  if (ctx.environment !== 'portal') return startStandalone(); // your own standalone mode
  on('pause', () => game.pause());
  on('resume', () => game.resume());
  await request('loading.finished');
  await request('gameplay.start');
  // ... the round ends
  await request('gameplay.stop');
  const result = await request('lb.submit', { score: 42 });
  console.log(result.accepted, result.reason);
}

main();