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() | 方法 | 获取错误信息 | 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-cn", // 在此处设置默认语言
};
</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'
}
// Customize the trigger for the visitor chat window
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}' // 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 方法动态设置客户信息,适用于先无感登录、在 SDK 加载后再设置的场景。
<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', // 服务端生成的 sbs_mm
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>
// 用户停留 30 秒后自动打开聊天窗口
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>
// Cookie 提示栏显示时,将角标上移
function onCookieBannerShow() {
if (window.__twt__api && window.__twt__api.setPosition) {
window.__twt__api.setPosition({ right: '20px', bottom: '80px' })
}
}
// Cookie 提示栏关闭后,恢复默认位置
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>
<!-- 此处粘贴安装代码 -->