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

如何在Next.js中禁用Google Translate以避免客户端错误?

解决Next.js 14应用中Google Translate引发的IndexSizeError问题

针对Google Translate注入导致的IndexSizeError,以下是几个经过验证的解决方案,覆盖配置层面和编程层面:

1. 细化HTML元素的禁用标记

仅给<html>和<body>加translate="no"可能不足以阻止Google Translate的深层注入,需要补充以下操作:

  • 在_document.tsx中,给所有核心容器(比如页面根容器、组件外层)也添加translate="no"属性
  • 在Head组件内加入meta标签明确告知Google Translate跳过整个站点:
// _document.tsx 中的 Head 组件内部
<Meta name="google" content="notranslate" />

2. 调整HTTP响应头配置

之前的CSP配置可能未精准针对Google Translate,修改next.config.js添加更明确的限制:

/** @type {import('next').NextConfig} */
const nextConfig = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          // 限制脚本加载范围,阻止Google Translate脚本注入
          {
            key: 'Content-Security-Policy',
            value: "script-src 'self' 'unsafe-eval' 'unsafe-inline'; object-src 'none'; frame-src 'none';",
          },
          // 声明站点不需要翻译
          {
            key: 'X-Robots-Tag',
            value: 'notranslate',
          },
          // 禁用翻译权限
          {
            key: 'Permissions-Policy',
            value: 'translate=()',
          },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

注意:根据你的实际脚本依赖调整script-src内容,避免影响应用正常功能。

3. 客户端编程移除Google Translate注入

如果上述配置仍无效,可在客户端渲染时主动检测并清理Google Translate的注入元素:

// 在_app.tsx的useEffect中添加
useEffect(() => {
  const cleanTranslateElements = () => {
    // 移除顶部翻译横幅
    const banner = document.querySelector('.goog-te-banner-frame');
    if (banner) {
      banner.remove();
      document.body.style.top = '0'; // 恢复页面原始位置
    }
    // 移除翻译小部件
    const gadget = document.querySelector('.goog-te-gadget');
    if (gadget) gadget.remove();
  };

  // 立即执行一次清理,再监听DOM变化持续处理
  cleanTranslateElements();
  const observer = new MutationObserver(cleanTranslateElements);
  observer.observe(document.body, { childList: true, subtree: true });

  return () => observer.disconnect();
}, []);

这段代码会持续监控DOM,一旦Google Translate注入元素就立即移除,避免其干扰页面布局和脚本执行。

4. 针对特定元素的精准禁用

如果不需要全站禁用,仅针对引发错误的元素,可以给该元素添加class="notranslate"或translate="no"属性,Google Translate会自动跳过这些元素的翻译。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:25:00