【问题标题】:Showing google Recaptcha V3 floater only on specific Pages of React Application仅在 React 应用程序的特定页面上显示 google Recaptcha V3 floater
【发布时间】:2020-04-17 06:07:27
【问题描述】:

我已经用多个#路由和谷歌recaptcha v3反应应用程序,

我只想在特定页面(#路由)上显示 recaptcha floater,例如登录和表单。

如何做到这一点。

试过了-

.grecaptcha-badge { 
    visibility: hidden;
}
#root #mainContainer .login:not(.empty) +  div>.grecaptcha-badge { 
    visibility: visible;
}

.grecaptcha-badge { 
    visibility: hidden;
}
#root #mainContainer .login ~ div>.grecaptcha-badge { 
    visibility: visible;
}

显示被 javascript 隐藏 > componentWillMount -> 页面的 componentwillmount 在 google recaptcha 呈现之前调用,所以它不会获取元素

【问题讨论】:

  • 使用 CSS 作为隐藏 recaptcha 元素的方式违反了 Google 服务条款 (policies.google.com/terms?hl=en),除非您以其他方式告知用户您正在使用 recaptcha。如果您的目标是简单地从某些页面中省略 recaptcha,那么我建议根本不渲染它们(在那些特定页面上)。

标签: javascript css reactjs invisible-recaptcha recaptcha-v3


【解决方案1】:

我(和其他许多人一样)有同样的问题。

在我的情况下,我使用 react-route 来监听路径变化。 所以我最终删除了我不需要的页面上的脚本和徽章元素,并在某些路径上添加它(如果需要)。

const loadRecaptcha = () => {
    const script = document.createElement("script");

    script.src = "https://www.google.com/recaptcha/api.js?render=lalala";
    script.id = 'recaptcha-script';
    script.async = true;

    document.body.append(script);
}

const removeRecaptcha = () => {
    const script = document.getElementById('recaptcha-script');
    if (script) {
        script.remove();
    }

    const recaptchaElems = document.getElementsByClassName('grecaptcha-badge');
    if (recaptchaElems.length) {
        recaptchaElems[0].remove();
    }
}

希望将来对某人有所帮助

【讨论】:

    【解决方案2】:

    在你的组件之外声明这个:

    const toggleCaptchaBadge = (show: boolean) => {
      const badge = document.getElementsByClassName('grecaptcha-badge')[0];
      if (badge && badge instanceof HTMLElement) {
        badge.style.visibility = show ? 'visible' : 'hidden';
      }
    };
    

    里面调用这个useEffect钩子:

    useEffect(() => {
        toggleCaptchaBadge(true);
        return () => toggleCaptchaBadge(false);
      }, []);
    

    【讨论】:

    • 这行得通,但在我读到的某个地方,隐藏recaptcha 是非法的,但这行得通
    【解决方案3】:

    如果我们希望在您的 react 应用中有条件地删除 Google 的 reCAPTCHA。我们可以使用 CDM() 生命周期方法来:

    1. 删除脚本
    2. 移除 reCAPTCHA 徽章

    我使用react-google-recaptcha-v3,并检查GoogleReCaptchaProvider的类,我们可以找到scriptId 和上面Ivan Yulin所说的完全一样。

    const script = document.querySelector(scriptId);
            if (script) {
                script.remove();
            }
            const recaptchaElems = document.getElementsByClassName('grecaptcha-badge');
            if (recaptchaElems.length) {
                recaptchaElems[0].remove();
            }
    

    但是,即使删除了我在 DOM 中看到的脚本

    <script id="google-recaptcha-v3" src="https://www.google.com/recaptcha/api.js?render=*********"></script>
    

    我们怎样才能把它也去掉?

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 2023-01-04
      • 2020-10-04
      • 2023-01-31
      相关资源
      最近更新 更多