The SDK is plain JavaScript living on window.WSG, so any engine that exports to HTML5 can use it. The general approach: load /sdk/v1/wsg-sdk.js in the exported index.html, then have your engine code call into JavaScript at the right moments of the game lifecycle.
Phaser 3
With the repository template
Games built inside the Leono Games repository use WsgPhaserPlugin from the internal @wsg/game-kit package: the plugin calls loadingProgress/loadingFinished from the Preload/Menu scenes and gameplayStart/gameplayStop from the Game scene, sleeps the loop and mutes audio on pause, and provides a this.wsg.submitScore() that never throws. See Quick start, part B.
Phaser without game-kit
@wsg/game-kit isn't published externally, but wiring Phaser to the SDK yourself only takes a few lines. The example below works with Phaser 3 loaded from a script tag (phaser.min.js inside your bundle) or through a bundler:
const GAME_ID = 'my-phaser-game';
let loadingDone = false;
let userMuted = false;
class Preload extends Phaser.Scene {
constructor() {
super('Preload');
}
preload() {
WSG.loadingStart();
this.load.on('progress', (value) => WSG.loadingProgress(value * 100));
// this.load.image('player', 'assets/player.png'); // relative paths only
}
create() {
this.scene.start('Menu');
}
}
class Menu extends Phaser.Scene {
constructor() {
super('Menu');
}
create() {
if (!loadingDone) {
loadingDone = true;
WSG.loadingFinished(); // only once, when the first menu appears
}
this.add.text(360, 640, 'Tap to play', { fontSize: '48px' }).setOrigin(0.5);
this.input.once('pointerdown', () => this.scene.start('Game'));
}
}
class Game extends Phaser.Scene {
constructor() {
super('Game');
}
create() {
this.score = 0;
this.scoreText = this.add.text(24, 24, '0', { fontSize: '40px' });
this.input.on('pointerdown', () => this.scoreText.setText(String(++this.score)));
this.time.delayedCall(10000, () => this.gameOver());
WSG.gameplayStart();
this.events.once('shutdown', () => WSG.gameplayStop());
}
async gameOver() {
WSG.gameplayStop();
this.scene.pause();
const result = await WSG.leaderboard.submit(this.score);
this.scene.launch('GameOver', { score: this.score, result });
}
}
class GameOver extends Phaser.Scene {
constructor() {
super('GameOver');
}
create({ score, result }) {
const line = result.accepted ? `#${result.rank}` : result.reason;
this.add.text(360, 600, `${score}\n${line}`, { fontSize: '40px', align: 'center' }).setOrigin(0.5);
this.input.once('pointerdown', async () => {
await WSG.ads.interstitial({ placement: 'between_rounds' });
this.scene.start('Game');
});
}
}
async function boot() {
await WSG.init({ gameId: GAME_ID });
const game = new Phaser.Game({
type: Phaser.AUTO,
parent: 'game',
backgroundColor: '#171430',
scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, width: 720, height: 1280 },
scene: [Preload, Menu, Game, GameOver],
});
WSG.on('pause', () => {
game.loop.sleep();
game.sound.mute = true;
});
WSG.on('resume', () => {
game.loop.wake();
game.sound.mute = userMuted;
});
WSG.on('audio', (enabled) => {
game.sound.mute = !enabled || userMuted;
});
}
boot();game.loop.sleep()stops the loop entirely (clocks, tweens, physics);game.loop.wake()resumes it.Menumay be created several times, so use a flag to callloadingFinished()only once.- With Vite, set
base: './'and keep the<script src="/sdk/v1/wsg-sdk.js">tag inindex.html; Vite will warn that it can't bundle that script tag, which is intended.
Canvas and plain JavaScript
The full example is in Quick start. The parts to keep:
let paused = false;
let last = 0;
WSG.on('pause', () => (paused = true));
WSG.on('resume', () => {
paused = false;
last = 0; // skip the time spent paused
});
function frame(ts) {
const dt = last ? Math.min(ts - last, 100) : 0; // clamp dt so a lag spike doesn't make things jump
last = ts;
if (!paused) update(dt);
render();
requestAnimationFrame(frame);
}Other engines through JavaScript
With Unity, Construct, Godot or any other engine, keep the code that talks to the SDK in JavaScript and let the engine call a few simple functions. Three things apply in every case:
- Add
<script src="/sdk/v1/wsg-sdk.js"></script>to the exportedindex.html, before the engine's scripts. - Call
WSG.init()early,loadingFinished()when the first screen is ready,gameplayStart()/gameplayStop()around each round, andleaderboard.submit()when a round ends. - Turn the SDK's
pause/resume/audioevents into the engine's own stop-the-loop and mute commands.
Check the size of your export: the engine's .wasm and data files usually make up most of the bundle, and the limit is 20 MB and 300 files (measured uncompressed). Strip unused modules, languages and fonts; if you are still over, talk to the operations team before submitting.
Note
Function names, build options and export settings change between engine versions. The snippets below only illustrate how to call back and forth with JavaScript; check them against the documentation of the engine version you use.
Unity WebGL
- C# calls JavaScript through a
.jslibplugin (placed in aPluginsfolder of your project) and functions declared with[DllImport("__Internal")]. Strings from C# arrive in JavaScript as pointers; read them withUTF8ToString(). - JavaScript calls back into C# with
SendMessage("GameObjectName", "MethodName", value). - Add the SDK script tag to the
index.htmlof your WebGL template (a custom template) or editindex.htmlafter building. - The games origin doesn't send
Content-Encoding, so a Brotli/Gzip-compressed build won't load unless Unity's decompression fallback is enabled; the simplest option is to build without compression for the portal.
mergeInto(LibraryManager.library, {
WsgInit: function (gameIdPtr) {
WSG.on('pause', function () {
SendMessage('WsgBridge', 'OnWsgPause');
});
WSG.on('resume', function () {
SendMessage('WsgBridge', 'OnWsgResume');
});
WSG.init({ gameId: UTF8ToString(gameIdPtr) }).then(function (ctx) {
SendMessage('WsgBridge', 'OnWsgReady', ctx.environment);
});
},
WsgLoadingFinished: function () {
WSG.loadingFinished();
},
WsgGameplayStart: function () {
WSG.gameplayStart();
},
WsgGameplayStop: function () {
WSG.gameplayStop();
},
WsgSubmitScore: function (score) {
WSG.leaderboard.submit(score).then(function (result) {
SendMessage('WsgBridge', 'OnWsgScore', JSON.stringify(result));
});
},
WsgShowRewarded: function () {
WSG.ads.rewarded({ placement: 'revive' }).then(function (result) {
SendMessage('WsgBridge', 'OnWsgRewarded', result.rewarded === true ? 'true' : 'false');
});
},
});using System.Runtime.InteropServices;
using UnityEngine;
// Attach to a GameObject named exactly "WsgBridge" in the first scene.
public class WsgBridge : MonoBehaviour
{
[DllImport("__Internal")] private static extern void WsgInit(string gameId);
[DllImport("__Internal")] private static extern void WsgLoadingFinished();
[DllImport("__Internal")] private static extern void WsgGameplayStart();
[DllImport("__Internal")] private static extern void WsgGameplayStop();
[DllImport("__Internal")] private static extern void WsgSubmitScore(int score);
[DllImport("__Internal")] private static extern void WsgShowRewarded();
void Start()
{
#if UNITY_WEBGL && !UNITY_EDITOR
WsgInit("my-unity-game");
#endif
}
// The methods below are called from JavaScript through SendMessage
void OnWsgReady(string environment) { WsgLoadingFinished(); }
void OnWsgPause() { Time.timeScale = 0f; AudioListener.pause = true; }
void OnWsgResume() { Time.timeScale = 1f; AudioListener.pause = false; }
void OnWsgScore(string resultJson) { Debug.Log("Score result: " + resultJson); }
void OnWsgRewarded(string rewarded) { if (rewarded == "true") { /* grant the reward */ } }
}Call WsgGameplayStart() when the player starts a round, then WsgGameplayStop() followed by WsgSubmitScore(score) when it ends. Play mode in the Unity Editor has no WSG, so wrap the calls in #if UNITY_WEBGL && !UNITY_EDITOR.
Construct 3
- Export with Web (HTML5), then add the SDK script tag to the exported
index.html, before Construct's own scripts. - Construct runs scripts inside a Web Worker when the Use worker project property is on, and from there
window.WSGisn't visible. Set Use worker to No so scripts can reach the SDK. - Call the SDK from script blocks in your event sheets; project global variables are available through
runtime.globalVars:
// When a round starts
WSG.gameplayStart();
// On game over (Score is a project global variable)
WSG.gameplayStop();
WSG.leaderboard.submit(Math.floor(runtime.globalVars.Score)).then((result) => {
runtime.globalVars.Rank = result.rank ?? 0;
});Call WSG.init() once when the project starts (for example in a script on the first layout) and WSG.loadingFinished() when the first screen appears. For pause/resume, set the project's time scale to 0 and back to 1 and mute audio with the matching actions.
Godot
- Export with the Web preset; add the SDK script tag through the preset's option for injecting code into
<head>, or with a custom HTML shell. - The games origin doesn't send cross-origin isolation headers (COOP/COEP), so an export that needs
SharedArrayBuffer(thread support on) won't run. Use a non-threaded export (available since Godot 4.3) or Godot 3. - Godot 4 talks to JavaScript through the
JavaScriptBridgesingleton (JavaScriptin Godot 3):eval()runs a snippet,get_interface()returns a JavaScript object,create_callback()creates a function JavaScript can call back. Keep a reference to the callback, or it will be released.
extends Node
var _on_result # keep a reference to the callback
func _ready() -> void:
if not OS.has_feature("web"):
return
JavaScriptBridge.eval("WSG.init({ gameId: 'my-godot-game' }).then(() => WSG.loadingFinished())", true)
func round_started() -> void:
JavaScriptBridge.eval("WSG.gameplayStart()", true)
func round_finished(score: int) -> void:
var wsg = JavaScriptBridge.get_interface("WSG")
wsg.gameplayStop()
_on_result = JavaScriptBridge.create_callback(_on_submit_result)
wsg.leaderboard.submit(score).then(_on_result)
func _on_submit_result(args: Array) -> void:
var result = args[0]
print("accepted: ", result.accepted, " rank: ", result.rank)