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

如何在Next.js的_document页面仅主域名加载聊天脚本

解决Next.js仅主域名加载指定脚本的问题

要实现仅在主域名(如domain.com)加载聊天窗口脚本,子域名(包括*.domain.com及子域名下所有路径)不加载的需求,可按以下方式修改代码:

实现思路

借助Next.js _document的服务端渲染特性,先获取当前请求的域名,精确判断是否为主域名,再动态控制脚本标签的渲染。

Pages Router 方案(适用于传统_document.js)

import { Html, Head, Main, NextScript } from 'next/document'
import React from 'react'

class Document extends React.Component {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    // 获取请求域名,服务端从req取,客户端降级用window
    const hostname = ctx.req 
      ? ctx.req.headers.host.split(':')[0] 
      : window.location.hostname
    // 精确匹配主域名,替换为你的实际域名
    const isMainDomain = hostname === 'domain.com'
    return { ...initialProps, isMainDomain }
  }

  render() {
    const { isMainDomain } = this.props
    return (
      <Html lang="en">
        <Head>
          {/* 仅主域名时渲染脚本 */}
          {isMainDomain && (
            <script src="//code.jivosite.com/widget/id" async></script>
          )}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default Document

App Router 方案(Next.js 13+)

如果使用App Router架构,可创建客户端组件动态插入脚本:

// app/components/ChatScript.js 标记为客户端组件
'use client'

import { useEffect } from 'react'

export default function ChatScript() {
  useEffect(() => {
    const hostname = window.location.hostname
    if (hostname === 'domain.com') {
      const script = document.createElement('script')
      script.src = '//code.jivosite.com/widget/id'
      script.async = true
      document.head.appendChild(script)
    }
  }, [])

  return null
}

在根layout.js中引入该组件:

// app/layout.js
import ChatScript from './components/ChatScript'

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>
        <ChatScript />
      </head>
      <body>{children}</body>
    </html>
  )
}

关键说明

  • 精确域名判断:用严格相等===匹配主域名,确保所有子域名都被排除。
  • 环境兼容:服务端通过请求头取域名,客户端降级使用window.location.hostname,覆盖所有渲染场景。

内容的提问来源于stack exchange,提问作者Omar Atef

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:28:15