Skip to main content

Host Callback

On the PC platform, host callbacks are implemented using the JavaScript callback function (Callback) pattern.

1 SDK Initialization Callback​

Callback function when SDK initialization is completed.

Function Signature

(hostHandle, error) => void

Parameter Description

parameterData TypeDescription
hostHandleTJHostHandleHost handle returned when initialization succeeds, null when it fails
errorHostRuntimeErrorError object when initialization fails, null when successful

Usage Example

TJHostHandle.initialize('sdk-key', 'sdk-secret', (hostHandle, error) => {
if (error) {
console.error('Initialization failed:', error);
return;
}

console.log('Initialization successful');
// Use hostHandle...
});

2 First Frame Rendering Callback​

Callback function when the first frame of the game is rendered.

Function Signature

() => void

Usage Example

gameHandle.setOnFirstFrameRenderedListener(() => {
console.log('First frame rendered');
// Hide loading screen, etc.
});

3 Game Package Download Callback​

A collection of callback functions during the game package download process.

3.1 onStart - Start Download​

Function Signature

() => void

3.2 onProgress - Download Progress​

Function Signature

(progress, totalBytesWritten, totalBytesExpected) => void

Parameter Description

parameterData TypeDescription
progressNumberDownload Progress (0-1)
totalBytesWrittenNumberDownloaded ByteDance Count
totalBytesExpectedNumberTotal ByteDance

3.3 onSuccess - Download successful​

Function Signature

() => void

3.4 onFailure - Download Failed​

Function Signature

(error) => void

Parameter Description

parameterData TypeDescription
errorErrorError Object

Usage Example

gameHandle.setOnGamePackageDownloadListener({
onStart: () => {
console.log('Download started');
},

onProgress: (progress, totalBytesWritten, totalBytesExpected) => {
const percent = (progress * 100).toFixed(2);
console.log(`Download progress: ${percent}%`);
},

onSuccess: () => {
console.log('Download completed');
},

onFailure: (error) => {
console.error('Download failed:', error);
}
});

4 Game Failure Callback​

Callback function when the game fails to run.

Function Signature

(error) => void

Parameter Description

parameterData TypeDescription
errorHostRuntimeErrorError Object

Usage Example

gameHandle.setOnHostFailureListener((error) => {
console.error('Game host failure:', error.code, error.message);
// Handle failure: show error UI, restart game, etc.
});

5 Menu Button Click Callback​

Callback function when the top-right menu button is clicked.

Function Signature

() => void

Usage Example

gameHandle.setOnTJMenuListener(() => {
console.log('Menu button clicked');
// Show menu UI
});

6 Close button click callback​

Callback function when the close button in the upper right corner is clicked.

Function Signature

() => void

Usage Example

gameHandle.setOnTJCloseListener(() => {
console.log('Close button clicked');
// Show confirmation dialog, close game, etc.
});

7 Custom Command Callback​

Callback function for handling custom commands in the game.

Function Signature

(request, handle) => void

Parameter Description

parameterData TypeDescription
requestObjectRequest Parameter Object
handleObjectCommand handling handle, containing success() and fail()

handle object method

  • handle.success(result) - returns a successful result

  • handle.fail(errorCode, errorMsg) - returns a failure result

Usage Example

gameHandle.setCustomCommandListener('login', (request, handle) => {
// Validate parameters
if (!request.username) {
handle.fail(20001, 'Username is required');
return;
}

// Process login
performLogin(request.username, request.password)
.then(result => {
handle.success({
userId: result.userId,
token: result.token
});
})
.catch(error => {
handle.fail(20002, error.message);
});
});

8 Custom Script Execution Callback​

Callback function after executing a custom script.

Function Signature

(result, error) => void

Parameter Description

parameterData TypeDescription
resultAnyScript execution result, null when failed
errorErrorError object when execution fails, null when successful

Usage Example

const script = `
console.log('Custom script running');
return { success: true, data: 'Hello' };
`;

gameHandle.runCustomScript(script, (result, error) => {
if (error) {
console.error('Script execution failed:', error);
return;
}

console.log('Script result:', result);
});

9 Privacy Permission Check Callback​

Callback function when checking system permissions.

Function Signature

(methodName, callback) => void

Parameter Description

parameterData TypeDescription
methodNameStringMethod name that requires permission check
callbackFunctionPermission check result callback(result) => {}

result object

{
passed: Boolean, // if passed
errorNo: Number, // error Number
errorMessage: String // error Message
}

Usage Example

const privacyChecker = {
requirePrivacy: (methodName, callback) => {
console.log(`Checking privacy for: ${methodName}`);

// Perform permission check
checkSystemPermission(methodName)
.then(() => {
callback({
passed: true,
errorNo: 0,
errorMessage: ''
});
})
.catch(error => {
callback({
passed: false,
errorNo: 1,
errorMessage: error.message
});
});
}
};

gameHandle.setPrivacyChecker(privacyChecker);

10 Complete Callback Example​

const { TJHostHandle } = require('webglhost-runtime-pc');

class GameCallbackManager {
constructor() {
this.gameHandle = null;
}

setupAllCallbacks(gameHandle) {
this.gameHandle = gameHandle;

// First frame rendered
gameHandle.setOnFirstFrameRenderedListener(() => {
this.onFirstFrameRendered();
});

// Download callbacks
gameHandle.setOnGamePackageDownloadListener({
onStart: () => this.onDownloadStart(),
onProgress: (p, w, t) => this.onDownloadProgress(p, w, t),
onSuccess: () => this.onDownloadSuccess(),
onFailure: (e) => this.onDownloadFailure(e)
});

// Game failure
gameHandle.setOnHostFailureListener((error) => {
this.onGameFailure(error);
});

// UI callbacks
gameHandle.setOnTJMenuListener(() => {
this.onMenuClicked();
});

gameHandle.setOnTJCloseListener(() => {
this.onCloseClicked();
});

// Custom command
gameHandle.setCustomCommandListener('myCommand', (request, handle) => {
this.handleCustomCommand(request, handle);
});

// Privacy checker
gameHandle.setPrivacyChecker({
requirePrivacy: (methodName, callback) => {
this.checkPrivacy(methodName, callback);
}
});
}

onFirstFrameRendered() {
console.log('First frame rendered');
}

onDownloadStart() {
console.log('Download started');
}

onDownloadProgress(progress, written, total) {
console.log(`Progress: ${(progress * 100).toFixed(2)}%`);
}

onDownloadSuccess() {
console.log('Download completed');
}

onDownloadFailure(error) {
console.error('Download failed:', error);
}

onGameFailure(error) {
console.error('Game failure:', error);
}

onMenuClicked() {
console.log('Menu clicked');
}

onCloseClicked() {
console.log('Close clicked');
}

handleCustomCommand(request, handle) {
// Process command
handle.success({ result: 'ok' });
}

checkPrivacy(methodName, callback) {
// Check permission
callback({ passed: true, errorNo: 0, errorMessage: '' });
}
}

// Usage
const callbackManager = new GameCallbackManager();
callbackManager.setupAllCallbacks(gameHandle);