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:
- You are inside an iframe:
window.parent !== window. - The
wsgquery parameter equals1. - The
hostquery parameter is a validhttporhttpsorigin.
Then send an init request. With no answer within 3 seconds, assume there is no portal and run your own standalone mode.
Envelope
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 uniqueidper request (for exampler1,r2), sent withwindow.parent.postMessage(msg, host). - Portal → game:
kind: 'res'with the sameidandtypeas the request; on success it carries apayload(always an object,{}when there is nothing), on failure anerror. The portal also sendskind: 'evt'messages on its own. - Messages with the wrong shape (
wsgother than1, missingkindortype) are silently ignored on both sides. payloadgoes throughpostMessage's structured clone: round-trip your data through JSON before sending to avoidDataCloneErroron functions or special objects.
Origin checks
- The game only accepts messages where
event.source === window.parentandevent.origin === host. - The portal only accepts messages from the game iframe's own
contentWindowwithevent.originequal tohttps://games.leonogames.com, and only sends to that origin. - Never use
'*'as thetargetOrigin: always passhost.
Timeouts
| Request | Timeout | When it expires |
|---|---|---|
init | 3 seconds | Run standalone |
ads.interstitial, ads.rewarded | 120 seconds | Treat as { shown: false, reason: 'error' } |
| Everything else | 10 seconds | A timeout error |
Requests from the game
type | payload | Returned payload | What 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? } | AdResult | placement at most 64 characters |
ads.rewarded | { placement? } | AdResult | Same as above |
lb.submit | { score, meta? } | SubmitResult | score 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
type | payload | When |
|---|---|---|
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 unknowntype, an invalidpayload, or data rejected by the API;not_initialized: the play session has ended (forlb.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
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
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();