Appearance
在 React 与 Next.js 项目中安装
接入代码是一段 script 标签,不需要装 npm 包。聊天窗是页面级的,加载一次就一直在,不要放进会随路由反复挂载的组件里。
React 项目:加在 index.html
在项目入口的 index.html 里,把接入代码加在 </body> 之前。用 Vite 创建的项目在根目录,用 Create React App 创建的项目在 public/index.html。
html
<!-- index.html -->
<body>
<div id="root"></div>
<script async
src="https://assets.aihecong.com/sdk/hecong.js"
data-channel-id="0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b">
</script>
<script>
window.hecong = window.hecong || function (c) { (window.hecong.q = window.hecong.q || []).push(c) }
</script>
</body>Next.js 项目
聊天窗依赖浏览器环境,不能在服务端执行。按项目用的路由方式选一种写法:
jsx
import Script from 'next/script'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Script
async
src="https://assets.aihecong.com/sdk/hecong.js"
data-channel-id="0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b"
strategy="afterInteractive"
/>
<Script id="hecong-stub" strategy="beforeInteractive">
{'window.hecong = window.hecong || function (c) { (window.hecong.q = window.hecong.q || []).push(c) }'}
</Script>
</body>
</html>
)
}jsx
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
<script
async
src="https://assets.aihecong.com/sdk/hecong.js"
data-channel-id="0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b"
/>
<script
dangerouslySetInnerHTML={{
__html: 'window.hecong = window.hecong || function (c) { (window.hecong.q = window.hecong.q || []).push(c) }',
}}
/>
</body>
</Html>
)
}示例里的渠道编号是演示用的,换成你在工作台复制到的那个。
装好之后
部署后打开网站,页面上出现聊天按钮就装好了。
本地开发时按钮不出现的,先看渠道有没有填授权域名,见本地开发与域名限制。
示例里那行占位函数照原样保留:之后在组件里调 window.hecong(cb) 传客户身份、打开聊天窗时,不用管接入脚本有没有加载完,写法见 React 与 Vue 接入示例。