JavaScript API
Use the APIs below when you need to customize the widget after the base installation is complete.
API Summary
| Name | Type | Description | Callback / Return |
|---|---|---|---|
__twt__sdk_ready | Event | SDK finished loading | e.detail.version, e.detail.timestamp |
__twt__sdk_error | Event | SDK loading error | e.detail.error.message |
__twt__custom_event | Event | Unread message count changed | e.detail.unread |
visibility_changed | Event | Chat window visibility changed | detail.visibility, detail.isOpen |
icon = '2' | Config | Custom launcher | — |
login(...) | Method | Set customer information | — |
setLanguage(lang) | Method | Set the UI language | — |
open() | Method | Open the chat window | — |
close() | Method | Close the chat window | — |
isOpen() | Method | Check window state | boolean |
hideBadge() | Method | Hide the badge (floating icon) | — |
setPosition(pos) | Method | Reposition the badge dynamically | — |
isReady() | Method | Check whether the SDK is ready | boolean |
onReady(callback) | Method | Register a ready callback | — |
getError() | Method | Get SDK error information | Object | null |
Supported language codes:
| Code | Language |
|---|---|
en | English |
zh-cn | 简体中文 |
zh-tw | 繁體中文 |
ja | 日本語 |
ko | 한국어 |
de | Deutsch |
fr | Français |
pt | Português |
ru | Русский |
Event Listeners
All event listeners must be registered before the SDK installation script loads, otherwise events may be missed. Correct code order: register listeners first, then load the SDK script.
Initialization & Language Setup
To set the default language when the widget loads, you can define lang directly in the __twt__config object within your installation snippet:
<script>
window.__twt__config = {
appid: "your-app-id",
lang: "en", // Set the default language here
};
</script>
SDK Ready Event
Fires when the SDK has finished loading and initialization is complete.
// Must be registered before the SDK loads
window.addEventListener('__twt__sdk_ready', (event) => {
console.log('SDK is ready')
console.log('Version:', event.detail.version)
console.log('Timestamp:', event.detail.timestamp)
})
💡 Example: Set the language and auto-login the user after SDK is ready:
<script>
// Must be registered before the SDK loads
window.addEventListener('__twt__sdk_ready', function (event) {
console.log('SDK ready, version:', event.detail.version)
// Auto-login if user is signed in
var currentUser = getLoggedInUser() // Your own function
if (currentUser && window.__twt__api && window.__twt__api.login) {
window.__twt__api.login(
currentUser.id,
currentUser.sign,
currentUser.rand,
currentUser.name,
currentUser.nickname
)
}
})
</script>
<!-- Paste your installation code here -->
SDK Error Event
Fires when the SDK fails to load or initialize.
// Must be registered before the SDK loads
window.addEventListener('__twt__sdk_error', (event) => {
console.log('SDK loading error:', event.detail.error.message)
})
💡 Example: Show a fallback contact method when the SDK fails to load:
<script>
// Must be registered before the SDK loads
window.addEventListener('__twt__sdk_error', function (event) {
console.log('SDK error:', event.detail.error.message)
var fallback = document.getElementById('fallback-contact')
if (fallback) {
fallback.style.display = 'block'
fallback.textContent = 'Live chat is unavailable. Please email support@example.com'
}
})
</script>
Unread Count Changes
Fires when the unread message count changes.
// Must be registered before the SDK loads
window.addEventListener('__twt__custom_event', (event) => {
console.log('Unread message count:', event.detail.unread)
})
💡 Example: Display an unread message badge on your custom chat button:
<button id="my-chat-btn">💬 Support <span id="unread-badge" style="display:none"></span></button>
<script>
// Must be registered before the SDK loads
window.addEventListener('__twt__custom_event', function (event) {
var badge = document.getElementById('unread-badge')
var count = event.detail.unread
if (count > 0) {
badge.textContent = count > 99 ? '99+' : count
badge.style.display = 'inline-block'
} else {
badge.style.display = 'none'
}
})
</script>
Visibility Changes
Use TWTChatWidget.on to listen for chat window visibility changes. This method can be called before the SDK loads — events are queued and replayed once the SDK is ready.
Possible visibility values:
maximized— the chat window is openminimized— the chat window is closed (badge still visible)hidden— the badge is hidden
// Must be initialized and registered before the SDK loads
window.TWTChatWidget = window.TWTChatWidget || {
_q: [],
on(eventName, callback) {
this._q.push(['on', [eventName, callback]])
},
}
window.TWTChatWidget.on('visibility_changed', (detail) => {
console.log('Visibility:', detail.visibility) // 'maximized' | 'minimized' | 'hidden'
console.log('Is open:', detail.isOpen) // true | false
})
💡 Example: Pause a hero video when the chat window opens and resume when it closes:
<script>
// Must be initialized and registered before the SDK loads
window.TWTChatWidget = window.TWTChatWidget || {
_q: [],
on(eventName, callback) {
this._q.push(['on', [eventName, callback]])
},
}
window.TWTChatWidget.on('visibility_changed', function (detail) {
var video = document.getElementById('hero-video')
if (!video) return
if (detail.visibility === 'maximized') {
video.pause()
} else if (detail.visibility === 'minimized') {
video.play()
}
})
</script>
Custom Launcher
Set icon to "2" to hide the default launcher in the lower-right corner, then use your own button to open the chat window.
Replace button with the ID of your own trigger element.
<script>
// Hide the default badge
if (window.__twt__config) {
window.__twt__config.icon = '2'
}
// Open the visitor chat window with your custom trigger
document.getElementById('button').addEventListener('click', function () {
if (window.__twt__api && window.__twt__api.open) {
window.__twt__api.open()
}
})
</script>
💡 Example: You have a custom "Contact Support" button and want to open the TWT chat window when users click it, without showing the default launcher:
<!-- Your custom button -->
<button id="my-support-btn">💬 Contact Support</button>
<script>
// Hide the default badge
if (window.__twt__config) {
window.__twt__config.icon = '2'
}
// Open the chat window when the custom button is clicked
document.getElementById('my-support-btn').addEventListener('click', function () {
if (window.__twt__api && window.__twt__api.open) {
window.__twt__api.open()
} else {
alert('Chat is still loading. Please try again.')
}
})
</script>
Set Customer Information
Sync the identity of signed-in users from your system into TWT Chat so agents can see who the visitor is inside the console.
Option 1: Static assignment during page load
Set customer information through window.__twt__config during page load. These fields must be assigned before the widget script initializes.
<script>
if (window.__twt__config) {
window.__twt__config.sbs = '{sbs}' // Unique customer identifier
window.__twt__config.sbs_mm = '{sbs_mm}' // Customer signature
window.__twt__config.ranstr = '{ranstr}' // Random string, recommended 16+ characters
window.__twt__config.name = '{name}' // Customer full name
window.__twt__config.nickname = '{nickname}' // Customer nickname
window.__twt__config.email = '{email}' // Customer email
window.__twt__config.phone = '{phone}' // Customer phone number
}
</script>
Option 2: Dynamic assignment after the widget loads
Call login after the widget is ready. This is useful when login state becomes available later.
<script>
if (window.__twt__api && window.__twt__api.login) {
window.__twt__api.login({sbs}, {sbs_mm}, {ranstr}, {name}, {nickname}, {email}, {phone})
}
</script>
💡 Example: After your user logs in, sync their identity to the support system so agents can see who they are:
<script>
// Must be registered before the SDK loads
window.addEventListener('__twt__sdk_ready', function () {
// Assume you have user info available (e.g. from a backend API)
var user = {
id: '10086',
sign: 'e04e335818b69b2abc56ba28b539d092', // Generated server-side
rand: 'abc123xyz456',
name: 'John Doe',
nickname: 'Johnny',
}
if (window.__twt__api && window.__twt__api.login) {
window.__twt__api.login(user.id, user.sign, user.rand, user.name, user.nickname)
console.log('User identity synced to support system')
}
})
</script>
sbs_mm signature rule
sbs_mm is used to verify customer identity and must be generated on the server side:
sbs_mm = md5( md5(sbs + '_' + AppSecret) + '_' + ranstr )
| Step | Action | Example |
|---|---|---|
| 1 | Concatenate sbs + _ + AppSecret | 1001_your_app_secret |
| 2 | MD5 the result from step 1 in lower-case 32-character format | a1b2c3d4... |
| 3 | Concatenate the step 2 hash + _ + ranstr | a1b2c3d4..._random16string |
| 4 | MD5 the result from step 3 in lower-case 32-character format | final sbs_mm value |
AppSecret is required to generate sbs_mm. Generate it in Settings > Developer Settings, calculate the signature on the server, and never expose AppSecret to frontend code.
Set Language
Switch the widget language at runtime without reloading the page.
if (window.__twt__api && window.__twt__api.setLanguage) {
window.__twt__api.setLanguage('en')
}
💡 Example: Your website has a language switcher — sync the chat widget language when the user changes languages:
<!-- Language switcher buttons -->
<button onclick="switchLang('en')">English</button>
<button onclick="switchLang('zh-cn')">简体中文</button>
<button onclick="switchLang('zh-tw')">繁體中文</button>
<button onclick="switchLang('ja')">日本語</button>
<button onclick="switchLang('ko')">한국어</button>
<button onclick="switchLang('de')">Deutsch</button>
<button onclick="switchLang('fr')">Français</button>
<button onclick="switchLang('pt')">Português</button>
<button onclick="switchLang('ru')">Русский</button>
<script>
function switchLang(lang) {
// Switch your website's own language...
// Sync the TWT chat widget language
if (window.__twt__api && window.__twt__api.setLanguage) {
window.__twt__api.setLanguage(lang)
console.log('Chat widget language changed to:', lang)
}
}
</script>
Chat Window Controls
Open Chat Window
if (window.__twt__api && window.__twt__api.open) {
window.__twt__api.open()
}
💡 Example: Auto-open the chat window after a user has been on the help page for 30 seconds:
<script>
setTimeout(function () {
if (window.__twt__api && window.__twt__api.open) {
window.__twt__api.open()
}
}, 30000)
</script>
Close Chat Window
if (window.__twt__api && window.__twt__api.close) {
window.__twt__api.close()
}
💡 Example: Automatically close the chat window after the user submits an order:
<script>
function onOrderSubmitted() {
if (window.__twt__api && window.__twt__api.close) {
window.__twt__api.close()
}
window.location.href = '/order/success'
}
</script>
Check Window State
if (window.__twt__api && window.__twt__api.isOpen) {
console.log('Chat window open:', window.__twt__api.isOpen())
}
💡 Example: Create a toggle button that opens the chat if closed and closes it if open:
<button id="toggle-chat">💬 Toggle Chat</button>
<script>
document.getElementById('toggle-chat').addEventListener('click', function () {
if (!window.__twt__api) return
if (window.__twt__api.isOpen && window.__twt__api.isOpen()) {
window.__twt__api.close()
} else {
window.__twt__api.open()
}
})
</script>
Hide Badge
Hide the floating badge icon. The chat window can still be opened programmatically via open().
if (window.__twt__api && window.__twt__api.hideBadge) {
window.__twt__api.hideBadge()
}
💡 Example: Hide the badge during fullscreen presentations:
<script>
document.addEventListener('fullscreenchange', function () {
if (document.fullscreenElement && window.__twt__api && window.__twt__api.hideBadge) {
window.__twt__api.hideBadge()
}
})
</script>
Reposition Badge
Reposition the badge (floating icon) dynamically.
if (window.__twt__api && window.__twt__api.setPosition) {
window.__twt__api.setPosition({ right: '20px', bottom: '20px' })
}
💡 Example: Move the badge up when a cookie consent banner is shown:
<script>
function onCookieBannerShow() {
if (window.__twt__api && window.__twt__api.setPosition) {
window.__twt__api.setPosition({ right: '20px', bottom: '80px' })
}
}
function onCookieBannerClose() {
if (window.__twt__api && window.__twt__api.setPosition) {
window.__twt__api.setPosition({ right: '20px', bottom: '20px' })
}
}
</script>
SDK Lifecycle
Check SDK Ready
if (window.__twt__api && window.__twt__api.isReady()) {
console.log('SDK is ready')
}
💡 Example: Check if the SDK is ready before calling other APIs:
<script>
function openChatSafely() {
if (window.__twt__api && window.__twt__api.isReady()) {
window.__twt__api.open()
} else {
console.log('SDK is not ready yet, please wait')
}
}
</script>
Register Ready Callback
Register a callback that runs when the SDK becomes ready. The callback receives the API object.
if (window.__twt__api && window.__twt__api.onReady) {
window.__twt__api.onReady((api) => {
console.log('SDK is ready', api)
})
}
💡 Example: Set the language and sync user info as soon as the SDK is ready:
<script>
if (window.__twt__api && window.__twt__api.onReady) {
window.__twt__api.onReady(function (api) {
api.login('10086', 'sign_hash', 'random_str', 'John Doe', 'Johnny')
console.log('SDK ready — initial configuration complete')
})
}
</script>
Get Error Info
Get the current SDK error information. Returns Object | null.
if (window.__twt__api && window.__twt__api.getError) {
console.log(window.__twt__api.getError())
}
💡 Example: Check SDK health and display a fallback contact method if it failed:
<script>
function checkSdkHealth() {
if (!window.__twt__api) {
console.log('SDK has not loaded')
return
}
var error = window.__twt__api.getError ? window.__twt__api.getError() : null
if (error) {
console.log('SDK error:', error.message)
document.getElementById('chat-status').textContent = 'Live chat is unavailable'
} else {
document.getElementById('chat-status').textContent = 'Support is online'
}
}
</script>
Full Integration Example
The following example shows the correct order for event listeners, configuration, and SDK loading:
<!-- Step 1: Register event listeners (must come before the SDK) -->
<script>
// Initialize the TWTChatWidget queue (must come before the SDK)
window.TWTChatWidget = window.TWTChatWidget || {
_q: [],
on(eventName, callback) {
this._q.push(['on', [eventName, callback]])
},
}
// Listen for visibility changes (must come before the SDK)
window.TWTChatWidget.on('visibility_changed', function (detail) {
console.log('Visibility:', detail.visibility, 'Is open:', detail.isOpen)
})
// Listen for SDK ready (must come before the SDK)
window.addEventListener('__twt__sdk_ready', function (event) {
console.log('SDK is ready, version:', event.detail.version)
})
// Listen for SDK errors (must come before the SDK)
window.addEventListener('__twt__sdk_error', function (event) {
console.log('SDK loading error:', event.detail.error.message)
})
// Listen for unread count changes (must come before the SDK)
window.addEventListener('__twt__custom_event', function (event) {
console.log('Unread count:', event.detail.unread)
})
</script>
<!-- Paste your installation code here -->