You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Smartsupp聊天插件集成到React技术栈的Gatsby站点中

实现方案:封装Smartsupp延迟加载组件

我们可以将聊天功能封装为独立的无渲染React组件,既满足延迟加载需求,也兼容Gatsby的SSR构建逻辑,同时避免硬编码dangerouslySetInnerHTML的不合理写法,复用性和可维护性更高。

import React, { useEffect } from 'react'

const SmartsuppChat = ({ smartsuppKey, delay = 5000 }) => {
  useEffect(() => {
    // 兼容Gatsby SSR构建场景,仅在客户端环境执行逻辑
    if (typeof window === 'undefined') return

    const loadTimer = setTimeout(() => {
      // 初始化Smartsupp基础配置
      window._smartsupp = window._smartsupp || {}
      window._smartsupp.key = smartsuppKey
      // 此处可添加其他官方支持的自定义配置
      // 例如:window._smartsupp.hideWidget = true

      // 官方原生脚本加载逻辑
      if (!window.smartsupp) {
        (function(d) {
          var s,c,o=window.smartsupp=function(){ o._.push(arguments)};o._=[];
          s=d.getElementsByTagName('script')[0];c=d.createElement('script');
          c.type='text/javascript';c.charset='utf-8';c.async=true;
          c.src='https://www.smartsuppchat.com/loader.js?';
          s.parentNode.insertBefore(c,s);
        })(document);
      }
    }, delay)

    // 组件卸载时清理定时器,避免内存泄漏
    return () => clearTimeout(loadTimer)
  }, [smartsuppKey, delay])

  // 组件无可视内容,直接返回null
  return null
}

export default SmartsuppChat

使用方法

全局加载(推荐)

在项目根目录的gatsby-browser.js中引入组件,即可实现全站生效:

import SmartsuppChat from './src/components/SmartsuppChat'

export const wrapRootElement = ({ element }) => {
  return (
    <>
      {element}
      <SmartsuppChat smartsuppKey="替换为你的Smartsupp密钥" delay={5000} />
    </>
  )
}

单页加载

如果仅需要在特定页面展示聊天功能,直接在对应页面组件内引入使用即可。

注意事项
  • 若要调整延迟时长,修改delay参数即可,单位为毫秒,默认值5000对应5秒延迟
  • 所有Smartsupp官方支持的自定义配置,都可以直接在初始化window._smartsupp的位置添加,规则和官方文档完全一致
  • 脚本为异步加载,不会阻塞站点主进程,不会影响首屏性能指标

内容的提问来源于stack exchange,提问作者Richard Rodrigues

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:39:01