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

React TypeScript中如何设置window.recaptchaOptions开启reCAPTCHA企业模式?

React中启用react-google-recaptcha企业模式的正确姿势

你的问题核心在于:window.recaptchaOptions必须在reCAPTCHA脚本加载前定义,否则设置不会生效。你之前用useEffect的方式是组件挂载后才执行,这时候react-google-recaptcha可能已经自动加载了普通版的api.js,所以企业模式的设置不会被识别。

下面分场景给出解决方案:

一、Next.js项目(对应你的_app.tsx场景)

方案1:在_document.tsx中提前定义全局变量

_document.tsx是Next.js中页面的根文档,脚本加载优先级最高,适合在这里提前设置全局选项:

// pages/_document.tsx
import Document, { Html, Head, Main, NextScript } from 'next/document';

declare global {
  interface Window { recaptchaOptions: { enterprise: boolean }; }
}

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          {/* 先定义全局选项,确保在reCAPTCHA脚本加载前生效 */}
          <script dangerouslySetInnerHTML={{
            __html: `
              window.recaptchaOptions = {
                enterprise: true
              };
            `
          }} />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

方案2:手动加载企业版脚本,完全控制时机

禁用组件的自动脚本加载,自己先设置全局选项再加载enterprise.js:

// _app.tsx
import { useEffect, useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';

declare global {
  interface Window { recaptchaOptions: { enterprise: boolean }; }
}

function MyApp({ Component, pageProps }) {
  const [captchaReady, setCaptchaReady] = useState(false);

  useEffect(() => {
    // 1. 先设置企业模式全局选项
    window.recaptchaOptions = { enterprise: true };
    // 2. 手动加载企业版脚本
    const script = document.createElement('script');
    script.src = 'https://www.google.com/recaptcha/enterprise.js';
    script.async = true;
    script.defer = true;
    script.onload = () => setCaptchaReady(true);
    document.body.appendChild(script);

    // 组件卸载时清理脚本
    return () => document.body.removeChild(script);
  }, []);

  return (
    <>
      <Component {...pageProps} />
      {/* 脚本加载完成后再渲染验证码组件 */}
      {captchaReady && (
        <ReCAPTCHA
          sitekey="你的企业版Site Key"
          asyncScriptOnLoad={false} // 禁用组件自动加载脚本
        />
      )}
    </>
  );
}

export default MyApp;

二、普通React项目(create-react-app)

直接在public/index.html的<head>中添加全局变量定义,确保在任何reCAPTCHA脚本之前执行:

<!-- public/index.html -->
<head>
  <!-- 提前设置企业模式 -->
  <script>
    window.recaptchaOptions = {
      enterprise: true
    };
  </script>
  <!-- 其他head内容 -->
</head>

关键注意点

  • 无论哪种方案,window.recaptchaOptions的定义必须早于reCAPTCHA脚本的加载,这是谷歌reCAPTCHA识别企业模式的核心要求
  • 启用企业模式后,必须使用谷歌后台生成的企业版Site Key,普通版Site Key无法在企业模式下使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:07:19