Minigame Management
1 Game Startup Parameter Settings
1.1 Initialize game startup parameters
Interface Prototype
gameHandle.setGameStartOptions(options)
Parameter Description
| parameter | Data Type | Required | Attribute Description |
|---|---|---|---|
launchKey | String | Yes | Game launch items, supporting three types: game list launch items, QR code scan launch items, and recent launch items. |
userId | String | Yes | Game User ID |
customScriptFiles | Array | No | List of js script file paths |
customScriptContents | Array | No | Javascript Text Content List |
enableVConsole | Boolean | No | Enable vConsole. Changing the enable or disable setting requires restarting the game. The default value is false |
enableInspector | Boolean | No | Enable Chrome DevTools debugging, default value is false |
waitForInspect | Boolean | No | Wait for DevTools to connect on startup, default value is false |
enableDomainWhiteList | Boolean | No | Enable the legal domain allowlist, with the default value being false |
domainWhiteListRequest | Array | No | Request legal domain names, starting with https://, up to 300 domain names can be filled in |
domainWhiteListSocket | Array | No | Valid socket domain names, starting with wss://, can have up to 200 domain names filled in |
domainWhiteListUDP | Array | No | Legal UDP domain names, starting with udp://, can have up to 200 domain names filled in. Note: IP addresses obtained through DNS resolution can also pass the allowlist |
domainWhiteListTCP | Array | No | tcp legal domain names, starting with tcp://, can fill in 200 domain names. Note: IP addresses obtained through DNS resolution can also pass the allowlist |
domainWhiteListUploadFile | Array | No | Legal domains for uploadFile, starting with https://, up to 200 domains can be filled in |
domainWhiteListDownloadFile | Array | No | Legal domains for downloadFile, starting with https://, up to 200 domains can be filled in |
enableReportMemory | Boolean | No | Statistics memory information, default value is false |
enableReportCpu | Boolean | No | Statistics cpu information, default value is false |
enableReportFps | Boolean | No | Statistics related to frame rate information, including fps, jank, and bigJank, with a default value of false |
splashGameTitle | String | No | Replace the game title on the Splash page |
splashIconUrl | String | No | Replace the game icon on the Splash page |
showMenuExploreBtn | Boolean | No | Open the top-right menu button. The default value is true |
showMenuLayout | Boolean | No | Enable top-right layout, default value is true |
enableTransparentMode | Boolean | No | Enable game transparent background, default value is false |
enableMuteAllAudio | Boolean | No | Enable audio mute, default value is false |
accessToken | String | No | Access token, used for in-game authentication |
Return value
ReturnsPromise<void>
Code Example
const { TJConstants } = require('webglhost-runtime-pc');
async function setupGame(gameHandle) {
const options = {
[TJConstants.LAUNCH_KEY]: 'your-launch-key',
[TJConstants.USER_ID]: 'guest-user',
[TJConstants.ENABLE_VCONSOLE]: true,
[TJConstants.ENABLE_INSPECTOR]: false,
[TJConstants.SHOW_MENU_LAYOUT]: true,
[TJConstants.CUSTOM_SCRIPT_FILES]: [
'/path/to/custom-script1.js',
'/path/to/custom-script2.js'
],
[TJConstants.DOMAIN_WHITELIST_REQUEST]: [
'https://api.example.com',
'https://cdn.example.com'
]
};
try {
await gameHandle.setGameStartOptions(options);
console.log('Game start options set successfully');
} catch (error) {
console.error('Failed to set game start options:', error);
throw error;
}
}
1.2 Explanation of Game Launch Parameter LAUNCH_KEY
Currently, the game supports three startup methods: startup from the game list, startup by scanning a QR code, and startup from the recently played list.
-
Game List Launch: The object returned by the game list interface contains the
launchKeyfield, which needs to be passed as a launch parameter toLAUNCH_KEYwhen launching the game.- launchKey:
67da9d2961b25a25faf0b143
- launchKey:
-
QR Code Scanning Launch: The result of scanning the QR code is passed as a launch parameter to
LAUNCH_KEY.- QR code scanning result:
https://minihost.tuanjie.cn/api/game_app/67da9d2961b25a25faf0b143/temp_session/a0f06587-3def-4a3a-95b2-89286bc325fa/start
- QR code scanning result:
-
Recently Played List Launch: The Recently Played Items also contain the
launchKeyfield, which is also passed as a launch parameter toLAUNCH_KEY. Refer to the Recently Played List-
launchKey when game list starts:
67da9d2961b25a25faf0b143 -
When the QR code scanning experience is launched, launchKey:
67da9d2961b25a25faf0b143:67dcc8227ae013b09d23ad23
-
2 Start the Game
Load and compile game resources, the game interface is visible but not interactive, and the host state changes to RUNNING.
Interface Prototype
gameHandle.start()
Return value
ReturnsPromise<void>
Code Example
async function startGame(gameHandle) {
try {
await gameHandle.start();
console.log('Game started successfully');
} catch (error) {
console.error('Failed to start game:', error);
throw error;
}
}
3 Run/Resume Game
The game can be interacted with or resume running when the application switches to the foreground, and the host state changes to PLAYING.
Interface Prototype
gameHandle.play()
Code Example
// Resume game when window gains focus
gameHandle.play();
console.log('Game resumed');
4 Pause Game
Game paused, host status changed to PAUSED.
Interface Prototype
gameHandle.pause()
Code Example
// Pause game when window loses focus
gameHandle.pause();
console.log('Game paused');
5 Stop the Game
Stop the game, and the host state changes to STOPPED.
Interface Prototype
gameHandle.stop()
Return value
ReturnsPromise<void>
Code Example
async function stopGame(gameHandle) {
try {
await gameHandle.stop();
console.log('Game stopped');
} catch (error) {
console.error('Failed to stop game:', error);
}
}
6 Restart the Game
Restart the game, retaining all startup parameters.
Interface Prototype
gameHandle.restart()
Return value
ReturnsPromise<void>
Code Example
async function restartGame(gameHandle) {
try {
await gameHandle.restart();
console.log('Game restarted');
} catch (error) {
console.error('Failed to restart game:', error);
}
}
7 Set Host First Frame Rendering Listener
Provides a callback after the host's first frame is rendered
Interface Prototype
gameHandle.setOnFirstFrameRenderedListener(callback)
Parameter Description
| parameter | Data Type | Required | Attribute Description |
|---|---|---|---|
callback | Function | Yes | First frame callback function |
Code Example
gameHandle.setOnFirstFrameRenderedListener(() => {
console.log('First frame rendered');
// Hide loading UI, show game UI, etc.
});
8 Set the callback for host game package download
Provides a callback mechanism for downloading the host game package. This callback will only be triggered when the game package is downloaded for the first time. If the game package is only read from the cache, this callback will not be triggered.
Interface Prototype
gameHandle.setOnGamePackageDownloadListener(callbacks)
Parameter Description
| parameter | Data Type | Required | Attribute Description |
|---|---|---|---|
callbacks.onStart | Function | Yes | Callback for the start of game package download () => {} |
callbacks.onProgress | Function | Yes | Game package download progress callback(progress, totalBytesWritten, totalBytesExpected) |
callbacks.onSuccess | Function | Yes | Callback for successful game package download () => {} |
callbacks.onFailure | Function | Yes | Game package download failure callback(error) => {} |
Parameter description for onProgress
-
progress: Download Progress (0-1)
-
totalBytesWritten: Downloaded size (ByteDance)
-
totalBytesExpected: Total file size (ByteDance)
Code Example
gameHandle.setOnGamePackageDownloadListener({
onStart: () => {
console.log('Game package download started');
},
onProgress: (progress, totalBytesWritten, totalBytesExpected) => {
const percent = (progress * 100).toFixed(2);
const downloadedMB = (totalBytesWritten / 1024 / 1024).toFixed(2);
const totalMB = (totalBytesExpected / 1024 / 1024).toFixed(2);
console.log(`Download progress: ${percent}% (${downloadedMB}MB / ${totalMB}MB)`);
},
onSuccess: () => {
console.log('Game package download completed');
},
onFailure: (error) => {
console.error('Game package download failed:', error);
}
});
9 Set up game failure monitoring
Provides a callback for game running failure
Interface Prototype
gameHandle.setOnHostFailureListener(callback)
Parameter Description
| parameter | Data Type | Required | Attribute Description |
|---|---|---|---|
callback | Function | Yes | Failure callback(error) => {} |
Code Example
gameHandle.setOnHostFailureListener((error) => {
console.error('Game host failure:', error);
// Handle error, show error UI, restart game, etc.
});
10 Audio Control
10.1 Mute All Audio
Interface Prototype
gameHandle.muteAllAudio()
Code Example
// Mute all game audio
gameHandle.muteAllAudio();
console.log('All audio muted');
10.2 Unmute
Interface Prototype
gameHandle.unmuteAllAudio()
Code Example
// Unmute all game audio
gameHandle.unmuteAllAudio();
console.log('All audio unmuted');
10.3 Toggle Mute State
Interface Prototype
gameHandle.toggleAudioMute()
Code Example
// Toggle audio mute state
gameHandle.toggleAudioMute();
console.log('Audio mute toggled');
10.4 Check Mute Status
Interface Prototype
gameHandle.isMuted()
Return value
Returns Boolean - Whether muted
Code Example
// Check if audio is muted
if (gameHandle.isMuted()) {
console.log('Audio is currently muted');
} else {
console.log('Audio is currently playing');
}
10.5 Complete Example of Audio Control
class AudioController {
constructor(gameHandle) {
this.gameHandle = gameHandle;
}
mute() {
this.gameHandle.muteAllAudio();
console.log('Muted');
}
unmute() {
this.gameHandle.unmuteAllAudio();
console.log('Unmuted');
}
toggle() {
this.gameHandle.toggleAudioMute();
console.log(`Audio is now ${this.gameHandle.isMuted() ? 'muted' : 'unmuted'}`);
}
getStatus() {
return this.gameHandle.isMuted() ? 'Muted' : 'Playing';
}
}
// Usage
const audioController = new AudioController(gameHandle);
// Mute audio
audioController.mute();
// Unmute audio
audioController.unmute();
// Toggle mute
audioController.toggle();
// Check status
console.log('Audio status:', audioController.getStatus());
11 Example of a Complete Game Lifecycle
const { TJHostHandle, TJConstants } = require('webglhost-runtime-pc');
class GameController {
constructor() {
this.hostHandle = null;
this.gameHandle = null;
}
async initialize(sdkKey, sdkSecret) {
// Initialize SDK
await new Promise((resolve, reject) => {
TJHostHandle.initialize(sdkKey, sdkSecret, (hostHandle, error) => {
if (error) {
reject(error);
return;
}
this.hostHandle = hostHandle;
resolve();
});
});
// Create game handle
this.gameHandle = await this.hostHandle.createGameHandle();
// Setup listeners
this.setupListeners();
}
setupListeners() {
// First frame rendered
this.gameHandle.setOnFirstFrameRenderedListener(() => {
console.log('Game first frame rendered');
});
// Download progress
this.gameHandle.setOnGamePackageDownloadListener({
onStart: () => console.log('Download started'),
onProgress: (progress) => console.log(`Progress: ${(progress * 100).toFixed(2)}%`),
onSuccess: () => console.log('Download completed'),
onFailure: (error) => console.error('Download failed:', error)
});
// Game failure
this.gameHandle.setOnHostFailureListener((error) => {
console.error('Game failure:', error);
});
}
async launchGame(launchKey, userId) {
// Set start options
await this.gameHandle.setGameStartOptions({
[TJConstants.LAUNCH_KEY]: launchKey,
[TJConstants.USER_ID]: userId,
[TJConstants.ENABLE_VCONSOLE]: true,
[TJConstants.SHOW_MENU_LAYOUT]: true
});
// Start game
await this.gameHandle.start();
// Play game
this.gameHandle.play();
console.log('Game launched successfully');
}
pauseGame() {
this.gameHandle.pause();
}
resumeGame() {
this.gameHandle.play();
}
async stopGame() {
await this.gameHandle.stop();
}
async restartGame() {
await this.gameHandle.restart();
}
async cleanup() {
if (this.gameHandle) {
await this.gameHandle.destroy();
}
}
}
// Usage
const controller = new GameController();
async function main() {
try {
await controller.initialize('sdk-key', 'sdk-secret');
await controller.launchGame('launch-key', 'user-id');
// Game is now running...
} catch (error) {
console.error('Error:', error);
}
}
main();