网页 JS SDK
单页应用(SPA)
在 React、Vue 等单页应用中使用 STINGIM 挂件:只安装一次、登录时 identify、登出与销毁。
挂件专为单页应用设计:它会自动感知 URL 和标题变化,将就绪前的调用放入队列,并且可以被干净地销毁。
基本原则
- 安装代码只插入一次,例如放在根布局中。路由切换无需额外代码。
- 用户登录或切换账号后,调用
stingIm.identify(user)。退出登录时调用stingIm.logout()。 - 如需彻底移除挂件(例如组件卸载时),调用
stingIm.destroy()。仅移除<script>标签并不会移除挂件。 - 重复插入脚本不会造成问题:第二次加载会复用已有实例。
React
JSX
import { useEffect } from 'react';
const INSTALL_SRC = 'https://app.stingim.com/chat-bubble/install.js?BASE64_PARAMS';
export function ChatWidget() {
useEffect(() => {
const s = document.createElement('script');
s.src = INSTALL_SRC;
s.async = true;
document.body.appendChild(s);
return () => {
window.stingIm?.destroy();
s.remove();
};
}, []);
return null;
}在登录状态变化时声明用户身份:
JSX
useEffect(() => {
if (!user) return;
fetch('/api/me/stingim-identity')
.then((r) => r.json())
.then(({ userId, userHash, exp }) =>
window.stingIm?.identify({ userId, userHash, exp, name: user.name, email: user.email }),
);
}, [user]);使用 TypeScript 时,声明一次全局类型:
TypeScript
declare global {
interface Window {
stingIm?: {
show(): void; hide(): void; open(): void; close(): void;
identify(u: { userId: string; userHash?: string; exp?: number; name?: string; email?: string }): Promise<boolean>;
logout(): Promise<boolean>;
setTags(tags: string[]): void;
setContext(ctx: { product?: string; orderNo?: string }): void;
setStyle(css: Record<string, string>): void;
getStatus(): { ready: boolean; visible: boolean; open: boolean; hidden: boolean;
identityStatus: 'anonymous' | 'verified' | 'unverified' | 'rejected' | null; error: string | null; destroyed: boolean };
onReady(cb: (api: NonNullable<Window['stingIm']>) => void): () => void;
destroy(): void;
};
stingImSettings?: Record<string, unknown>;
}
}
export {};Vue 3
JavaScript
import { onMounted, onBeforeUnmount } from 'vue';
export function useStingim(src) {
let script;
onMounted(() => {
script = document.createElement('script');
script.src = src;
script.async = true;
document.body.appendChild(script);
});
onBeforeUnmount(() => {
window.stingIm?.destroy();
script?.remove();
});
}Next.js
在根布局中用 next/script 加载一次脚本,它只会在浏览器中运行:
JSX
import Script from 'next/script';
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Script src="https://app.stingim.com/chat-bubble/install.js?BASE64_PARAMS" strategy="afterInteractive" />
</body>
</html>
);
}共享设备上退出登录
JavaScript
async function signOut() {
await window.stingIm?.logout(); // 下一位使用者将作为新的匿名访客开始
await api.logout();
}发现错误?请发邮件至 [email protected]
