ReCaptcha3:用户执行操作时如何调用执行? [英] ReCaptcha3: How to call execute when user takes the action?

查看:206
本文介绍了ReCaptcha3:用户执行操作时如何调用执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当包含这样的代码时,我设法使ReCaptcha3正常工作:

I managed to get ReCaptcha3 working when including it like this:

<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>

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

However, in the docs I found the following note:

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

Note: reCAPTCHA tokens expire after two minutes. If you're protecting an action with reCAPTCHA, make sure to call execute when the user takes the action.

由于我在联系表单上使用了reCAPTCHA,因此用户可能要花两分钟多的时间才能写东西.

Since I use the reCAPTCHA on a contact form, its likely that a user will take more then two minutes to write something.

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

Therefore, I tried to execute the key on submit (the alerts are only for testing):

<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>

现在会提示"Hi",但不会显示"Iam invisible".因此,它在服务器端得到了missing-input-response.为什么then内未触发then?

Now "Hi" is promted, but "Iam invisible" won't show up. Thus, it I get a missing-input-response on the server side. Why is then not fired inside addEventListener?

推荐答案

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

The problem is that the form is submitted before the async call grecaptcha.execute is complete. To fix the issue, one need to submit it manually:

<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>

这篇关于ReCaptcha3:用户执行操作时如何调用执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆