【问题标题】:ReCaptcha3: How to call execute when user takes the action?ReCaptcha3:当用户采取行动时如何调用执行?
【发布时间】:2020-02-04 23:57:41
【问题描述】:

我设法让 ReCaptcha3 像这样包含它:

<script src="https://www.google.com/recaptcha/api.js?render=mykey"></script>
<script>
  grecaptcha.ready(function() {
    grecaptcha.execute('mykey', {action: 'homepage'}).then(function(token) {
       document.getElementById("googletoken").value= token;
    });
</script>

但是,在docs 中我发现了以下注释:

注意:reCAPTCHA 令牌会在两分钟后过期。如果您使用 reCAPTCHA 保护操作,请确保在用户执行操作时调用 execute。

由于我在联系表单上使用 reCAPTCHA,因此用户可能需要两分钟以上的时间来写一些东西。

因此,我尝试在提交时执行密钥(警报仅用于测试):

<script src="https://www.google.com/recaptcha/api.js?render=mykey"></script>
<script>
  grecaptcha.ready(function() {
      document.getElementById('contactform').addEventListener("submit", function(event) {
        alert('hi');
        grecaptcha.execute('mykey', {action: 'homepage'}).then(function(token) {
           alert('Iam invisible');
           document.getElementById("googletoken").value= token;
        });
      }, false);
  });
</script>

现在“嗨”被提示,但“我看不见”不会出现。因此,我在服务器端得到一个missing-input-response。为什么then 没有在addEventListener 内部被触发?

【问题讨论】:

  • 你的控制台日志说什么?谷歌有电话吗?您是否在“mykey”中设置了密钥?
  • @db1975 似乎grecaptcha.execute 没有执行并提交了表单。我已正确设置密钥,第一个顶级版本按预期工作。

标签: javascript recaptcha-v3


【解决方案1】:

问题是在异步调用grecaptcha.execute 完成之前提交了表单。要解决此问题,需要手动提交:

<script src="https://www.google.com/recaptcha/api.js?render=mykey"></script>
<script>
  grecaptcha.ready(function() {
      document.getElementById('contactform').addEventListener("submit", function(event) {

        event.preventDefault();

        grecaptcha.execute('mykey', {action: 'homepage'}).then(function(token) {

           document.getElementById("googletoken").value= token; 
           document.getElementById('contactform').submit();
        });

      }, false);

  });
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2023-03-28
    • 2023-03-21
    相关资源
    最近更新 更多