JavaScript API
完成基礎安裝後,如需自訂聊天元件,可使用以下 API。
API 一覽
| 名稱 | 類型 | 說明 | 回呼參數 / 回傳值 |
|---|---|---|---|
__twt__sdk_ready | 事件 | SDK 載入完成 | e.detail.version, e.detail.timestamp |
__twt__sdk_error | 事件 | SDK 載入出錯 | e.detail.error.message |
__twt__custom_event | 事件 | 未讀訊息數變化 | e.detail.unread |
visibility_changed | 事件 | 聊天視窗可見性變化 | detail.visibility, detail.isOpen |
icon = '2' | 設定 | 自訂圖示 | — |
login(...) | 方法 | 設定客戶資訊 | — |
setLanguage(lang) | 方法 | 設定語言 | — |
open() | 方法 | 開啟聊天視窗 | — |
close() | 方法 | 關閉聊天視窗 | — |
isOpen() | 方法 | 檢查聊天視窗是否開啟 | boolean |
hideBadge() | 方法 | 隱藏角標(浮窗圖示) | — |
setPosition(pos) | 方法 | 動態設定角標位置 | — |
isReady() | 方法 | 檢查 SDK 是否就緒 | boolean |
onReady(callback) | 方法 | 註冊就緒回呼 | — |
getError() | 方法 | 取得 SDK 錯誤資訊 | Object | null |
支援的語言代碼:
| 語言代碼 | 語言 |
|---|---|
en | English |
zh-cn | 简体中文 |
zh-tw | 繁體中文 |
ja | 日本語 |
ko | 한국어 |
de | Deutsch |
fr | Français |
pt | Português |
ru | Русский |
事件監聽
所有事件監聽器必須在 SDK 安裝腳本之前註冊,否則可能會錯過事件。正確的程式碼順序:先註冊監聽器,再載入 SDK 腳本。
初始化與語言設定
要在元件載入時設定預設語言,可以直接在安裝程式碼的 __twt__config 物件中配置 lang 屬性:
<script>
window.__twt__config = {
appid: "你的專案APPID",
lang: "zh-tw", // 在此處設定預設語言
};
</script>
SDK 載入完成事件
當 SDK 載入完成並初始化成功時觸發。
// 注意:必須在 SDK 載入之前註冊監聽器
window.addEventListener('__twt__sdk_ready', (event) => {
console.log('SDK 已載入完成')
console.log('版本:', event.detail.version)
console.log('時間戳:', event.detail.timestamp)
})
💡 示例場景: SDK 就緒後設定語言並自動登入使用者:
<script>
// 注意:必須在 SDK 載入之前註冊監聽器
window.addEventListener('__twt__sdk_ready', function (event) {
console.log('SDK 已就緒,版本:', event.detail.version)
// 如果使用者已登入,自動同步身份資訊
var currentUser = getLoggedInUser() // 你自己的函式
if (currentUser && window.__twt__api && window.__twt__api.login) {
window.__twt__api.login(
currentUser.id,
currentUser.sign,
currentUser.rand,
currentUser.name,
currentUser.nickname
)
}
})
</script>
<!-- 此處貼上安裝程式碼 -->
SDK 錯誤事件
當 SDK 載入或初始化出錯時觸發。
// 注意:必須在 SDK 載入之前註冊監聽器
window.addEventListener('__twt__sdk_error', (event) => {
console.log('SDK 載入錯誤:', event.detail.error.message)
})
💡 示例場景: 載入失敗時顯示備用聯繫方式:
<script>
// 注意:必須在 SDK 載入之前註冊監聽器
window.addEventListener('__twt__sdk_error', function (event) {
console.log('SDK 載入錯誤:', event.detail.error.message)
var fallback = document.getElementById('fallback-contact')
if (fallback) {
fallback.style.display = 'block'
fallback.textContent = '線上客服暫不可用,請發送郵件至 support@example.com'
}
})
</script>
未讀訊息變化
當有新的未讀訊息時觸發。
// 注意:必須在 SDK 載入之前註冊監聽器
window.addEventListener('__twt__custom_event', (event) => {
console.log('未讀訊息數:', event.detail.unread)
})
💡 示例場景: 在自訂按鈕上顯示未讀訊息數角標:
<button id="my-chat-btn">💬 聯繫客服 <span id="unread-badge" style="display:none"></span></button>
<script>
// 注意:必須在 SDK 載入之前註冊監聽器
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>
視窗狀態變化
透過 TWTChatWidget.on 監聽聊天視窗的可見性變化。此方法支援在 SDK 載入之前呼叫,事件會被排隊緩存,待 SDK 就緒後自動消費。
visibility 的可能值:
maximized— 聊天視窗已開啟minimized— 聊天視窗已關閉(角標仍然可見)hidden— 角標已隱藏
// 注意:必須在 SDK 載入之前初始化並註冊監聽器
window.TWTChatWidget = window.TWTChatWidget || {
_q: [],
on(eventName, callback) {
this._q.push(['on', [eventName, callback]])
},
}
window.TWTChatWidget.on('visibility_changed', (detail) => {
console.log('可見性:', detail.visibility) // 'maximized' | 'minimized' | 'hidden'
console.log('是否開啟:', detail.isOpen) // true | false
})
💡 示例場景: 聊天視窗開啟時暫停頁面影片播放,關閉時恢復:
<script>
// 注意:必須在 SDK 載入之前初始化並註冊監聽器
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>
自訂圖示
將 icon 設為 "2" 可隱藏右下角預設浮窗圖示,之後可透過自訂按鈕開啟聊天視窗。
button 需替換為對應觸發元素的 ID。
<script>
// Hide default badge
if (window.__twt__config) {
window.__twt__config.icon = '2'
}
// Open the visitor chat window with a custom trigger
document.getElementById('button').addEventListener('click', function () {
if (window.__twt__api && window.__twt__api.open) {
window.__twt__api.open()
}
})
</script>
💡 示例場景: 你有一個自訂的「聯繫客服」按鈕,希望點擊時開啟 TWT 聊天視窗,而不顯示右下角預設浮窗:
<!-- 你的自訂按鈕 -->
<button id="my-support-btn">💬 聯繫客服</button>
<script>
// 隱藏預設角標
if (window.__twt__config) {
window.__twt__config.icon = '2'
}
// 點擊自訂按鈕時開啟聊天視窗
document.getElementById('my-support-btn').addEventListener('click', function () {
if (window.__twt__api && window.__twt__api.open) {
window.__twt__api.open()
} else {
alert('客服系統正在載入,請稍後再試')
}
})
</script>
設定客戶資訊
將你系統中已登入使用者的身份同步到 TWT Chat,讓客服可在工作台中直接查看訪客資訊。
方式一:頁面載入時靜態設定
在頁面載入時透過 window.__twt__config 設定客戶資訊,這些欄位必須在 SDK 腳本載入之前完成設定。
<script>
if (window.__twt__config) {
window.__twt__config.sbs = '{sbs}' // 使用者唯一識別
window.__twt__config.sbs_mm = '{sbs_mm}' // 使用者簽名
window.__twt__config.ranstr = '{ranstr}' // 隨機字串(建議 16 位以上)
window.__twt__config.name = '{name}' // 使用者姓名
window.__twt__config.nickname = '{nickname}' // 使用者暱稱
window.__twt__config.email = '{email}' // 使用者電子郵件
window.__twt__config.phone = '{phone}' // 使用者電話
}
</script>
方式二:載入後動態設定
在小部件載入完成後呼叫 login,適合登入狀態稍後才取得的場景。
<script>
if (window.__twt__api && window.__twt__api.login) {
window.__twt__api.login({sbs}, {sbs_mm}, {ranstr}, {name}, {nickname}, {email}, {phone})
}
</script>
💡 示例場景: 你的網站使用者在登入後,需要將身份資訊同步給客服系統:
<script>
// 注意:必須在 SDK 載入之前註冊監聽器
window.addEventListener('__twt__sdk_ready', function () {
var user = {
id: '10086',
sign: 'e04e335818b69b2abc56ba28b539d092',
rand: 'abc123xyz456',
name: '張三',
nickname: '三哥',
}
if (window.__twt__api && window.__twt__api.login) {
window.__twt__api.login(user.id, user.sign, user.rand, user.name, user.nickname)
console.log('已將使用者資訊同步到客服系統')
}
})
</script>
sbs_mm 簽名規則
sbs_mm 用於驗證使用者身份,必須在伺服器端生成:
sbs_mm = md5( md5(sbs + '_' + AppSecret) + '_' + ranstr )
| 步驟 | 操作 | 範例 |
|---|---|---|
| 1 | 拼接 sbs + _ + AppSecret | 1001_your_app_secret |
| 2 | 對步驟 1 結果取 MD5(小寫 32 位) | a1b2c3d4... |
| 3 | 拼接步驟 2 結果 + _ + ranstr | a1b2c3d4..._random16string |
| 4 | 對步驟 3 結果取 MD5(小寫 32 位) | 最終 sbs_mm 值 |
AppSecret 是生成 sbs_mm 的必要參數。請在 設定 > 開發設定 中生成,務必在伺服器端完成簽名計算,切勿將 AppSecret 暴露到前端程式碼中。
設定語言
設定語言,在執行階段切換聊天元件語言,無需重新載入頁面。
if (window.__twt__api && window.__twt__api.setLanguage) {
window.__twt__api.setLanguage('en')
}
💡 示例場景: 你的網站有語言切換功能,當使用者切換語言時同步更新聊天元件的語言:
<!-- 語言切換按鈕 -->
<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) {
// 同步切換 TWT 聊天元件的語言
if (window.__twt__api && window.__twt__api.setLanguage) {
window.__twt__api.setLanguage(lang)
console.log('聊天元件語言已切換為:', lang)
}
}
</script>
聊天視窗控制
開啟聊天視窗
if (window.__twt__api && window.__twt__api.open) {
window.__twt__api.open()
}
💡 示例場景: 使用者瀏覽了幫助頁面 30 秒後,自動彈出聊天視窗:
<script>
setTimeout(function () {
if (window.__twt__api && window.__twt__api.open) {
window.__twt__api.open()
}
}, 30000)
</script>
關閉聊天視窗
if (window.__twt__api && window.__twt__api.close) {
window.__twt__api.close()
}
💡 示例場景: 使用者提交訂單後,自動關閉聊天視窗:
<script>
function onOrderSubmitted() {
if (window.__twt__api && window.__twt__api.close) {
window.__twt__api.close()
}
window.location.href = '/order/success'
}
</script>
檢查視窗狀態
if (window.__twt__api && window.__twt__api.isOpen) {
console.log('聊天視窗是否開啟:', window.__twt__api.isOpen())
}
💡 示例場景: 做一個開關按鈕,點擊時如果已開啟就關閉,關閉就開啟:
<button id="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>
隱藏角標
隱藏右下角的浮窗角標。呼叫後聊天視窗仍然可以透過 open() 方法開啟。
if (window.__twt__api && window.__twt__api.hideBadge) {
window.__twt__api.hideBadge()
}
💡 示例場景: 在全螢幕演示模式下隱藏角標:
<script>
document.addEventListener('fullscreenchange', function () {
if (document.fullscreenElement && window.__twt__api && window.__twt__api.hideBadge) {
window.__twt__api.hideBadge()
}
})
</script>
設定角標位置
if (window.__twt__api && window.__twt__api.setPosition) {
window.__twt__api.setPosition({ right: '20px', bottom: '20px' })
}
💡 示例場景: 頁面底部有一個固定的 Cookie 提示欄,為了避免遮擋,將角標上移:
<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 生命週期
檢查 SDK 就緒
if (window.__twt__api && window.__twt__api.isReady()) {
console.log('SDK 已載入完成')
}
💡 示例場景: 在呼叫其他 API 之前,先檢查 SDK 是否就緒:
<script>
function openChatSafely() {
if (window.__twt__api && window.__twt__api.isReady()) {
window.__twt__api.open()
} else {
console.log('SDK 尚未就緒,請稍後')
}
}
</script>
註冊就緒回呼
if (window.__twt__api && window.__twt__api.onReady) {
window.__twt__api.onReady((api) => {
console.log('SDK 已載入完成', api)
})
}
💡 示例場景: SDK 就緒後立即同步使用者資訊並設定語言:
<script>
if (window.__twt__api && window.__twt__api.onReady) {
window.__twt__api.onReady(function (api) {
api.login('10086', 'sign_hash', 'random_str', '張三', '三哥')
console.log('SDK 就緒,已完成初始化設定')
})
}
</script>
取得錯誤資訊
取得 SDK 錯誤資訊。回傳值:Object | null。
if (window.__twt__api && window.__twt__api.getError) {
console.log(window.__twt__api.getError())
}
💡 示例場景: 檢查 SDK 是否載入出錯並提示使用者:
<script>
function checkSdkHealth() {
if (!window.__twt__api) {
console.log('SDK 尚未載入')
return
}
var error = window.__twt__api.getError ? window.__twt__api.getError() : null
if (error) {
console.log('SDK 載入出錯:', error.message)
document.getElementById('chat-status').textContent = '客服系統暫時不可用'
} else {
document.getElementById('chat-status').textContent = '客服在線'
}
}
</script>
完整整合範例
以下範例展示了事件監聽、設定與 SDK 載入的正確順序:
<!-- 第 1 步:註冊事件監聽(必須在 SDK 載入之前) -->
<script>
// 初始化 TWTChatWidget 佇列(必須在 SDK 載入之前)
window.TWTChatWidget = window.TWTChatWidget || {
_q: [],
on(eventName, callback) {
this._q.push(['on', [eventName, callback]])
},
}
// 監聽視窗狀態變化(必須在 SDK 載入之前)
window.TWTChatWidget.on('visibility_changed', function (detail) {
console.log('可見性:', detail.visibility, '是否開啟:', detail.isOpen)
})
// 監聽 SDK 就緒(必須在 SDK 載入之前)
window.addEventListener('__twt__sdk_ready', function (event) {
console.log('SDK 已載入完成,版本:', event.detail.version)
})
// 監聽 SDK 錯誤(必須在 SDK 載入之前)
window.addEventListener('__twt__sdk_error', function (event) {
console.log('SDK 載入錯誤:', event.detail.error.message)
})
// 監聽未讀訊息變化(必須在 SDK 載入之前)
window.addEventListener('__twt__custom_event', function (event) {
console.log('未讀訊息數:', event.detail.unread)
})
</script>
<!-- 此處貼上安裝程式碼 -->