在下一个 js 中显式呈现 google recaptcha enterprise widget

问题描述 投票:0回答:0

我正在尝试使用 google recaptcha enterprise 保护我的 next-js 网页上的表单。 我想手动渲染徽标,因为侧面的自动徽章会干扰我的布局/设计。

我将以下内容添加到我的表单页面:

const key="my-key"

useEffect(() => {
    (window as any).onloadCallback = () => {
      console.log("onloadCallback");
      (window as any).grecaptcha.enterprise.render(captchaRef.current,{sitekey: key});
      });
    };

    // Load reCAPTCHA script dynamically  
    const script = document.createElement('script');
    script.src = 'https://www.google.com/recaptcha/enterprise.js?onload=onloadCallback&render=explicit';
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);
  
    // Clean up the function on component unmount
    // (...)
}

// Form Submit method
const onSubmit: SubmitHandler<OrderFormInput> = async (data) => {
    // GetCaptchaToken
    const token = await (window as any).grecaptcha.enterprise.execute(key, {
      action: "place_order",
    });
    data.recaptchaToken = token;

    // debug
    console.log(token)

    // Call backend
    // (...)
}

有了这个,我在小部件中收到一条错误消息: Widget when explicitly rendering

还有

onSubmit()
我得到一个错误
[Error] Unhandled Promise Rejection: Error: Invalid site key or not loaded in api.js: <my-key>

当我使用时:

script.src = 'https://www.google.com/recaptcha/enterprise.js?render=<my-key>'

我得到一个正常的徽章和一个有效的令牌,我的后端也可以验证它。

Javascript API(->渲染方法)是否有可能被破坏? 至少对我来说,引用 api.js 而不是 enterprise.js 的错误代码看起来像是基于过时的代码。 在 recaptcha enterprise 之前,人们曾经从

https://www.google.com/recaptcha/api.js
..

获取脚本

关于要显式呈现的 Javascript API 的文档页面位于: https://cloud.google.com/recaptcha-enterprise/docs/api-ref-checkbox-keys

我通过 gcloud 控制台创建了多个站点密钥,并尝试了脚本 URL 的各种变体。

我还像这样包装了渲染调用:

(window as any).grecaptcha.enterprise.ready(() => {
    try{
        (window as any).grecaptcha.enterprise.render(captchaRef.current,{sitekey: key});
    }catch(e){
        console.log(e);
    }
});
google-cloud-platform next.js recaptcha recaptcha-enterprise
© www.soinside.com 2019 - 2024. All rights reserved.