Skip to main content

JavaScript API

When the TWT Chat SDK finishes loading, it exposes a __twt__api object on window for programmatic control.

Chat Window Controls

open()

Open the chat window.

window.__twt__api.open();

close()

Close the chat window.

window.__twt__api.close();

Language

setLanguage(lang)

Change the UI language without reloading the page.

  • Parameter: lang - supported values are zh-cn, zh-tw, and en
window.__twt__api.setLanguage('en');

Customer Identity

login(sbs, sbs_mm, ranstr, name, nickname, email, phone)

Set customer information dynamically after the SDK has loaded.

window.__twt__api.login(
'1001', // sbs - unique customer identifier
'a1b2c3d4...', // sbs_mm - customer signature
'random16str', // ranstr - random string
'Jane Doe', // name - customer full name
'VIP', // nickname - customer nickname
'jane@test.com', // email - email address
'13800138000' // phone - phone number
);

For sbs_mm signature rules, see Configuration Reference - sbs_mm Signature Rule.

SDK Lifecycle

isReady()

Check whether the SDK is ready.

  • Returns: boolean - whether the SDK is ready
if (window.__twt__api.isReady()) {
console.log('SDK is ready');
} else {
console.log('SDK is not ready');
}

onReady(callback)

Register a callback that runs when the SDK becomes ready. The callback receives the API object.

if (window.__twt__api.onReady) {
window.__twt__api.onReady(() => {
console.log('SDK is ready');
// TODO: your business logic
});
}

getError()

Get the current SDK error information.

  • Returns: Object | null - error object or null
window.__twt__api.getError();

Events

SDK Ready Event

warning

Place this code after the widget installation script.

window.addEventListener('__twt__sdk_ready', () => {
console.log('SDK is ready');
});

Unread Count Event

warning

Place this code after the widget installation script.

window.addEventListener('__twt__custom_event', (e) => {
console.log('Unread message count:', e.detail.unread);
});

API Summary

MethodDescriptionReturn Value
open()Open the chat window
close()Close the chat window
setLanguage(lang)Switch the UI language
login(sbs, sbs_mm, ...)Set customer information dynamically
isReady()Check whether the SDK is readyboolean
onReady(callback)Register a readiness callback
getError()Get current error informationObject | null
EventDescriptionCallback Payload
__twt__sdk_readySDK loaded successfully
__twt__custom_eventUnread message count changede.detail.unread