javascript - 验证码3 : How to call execute when user takes the action?

标签 javascript recaptcha-v3

我成功地让 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我发现以下注释:

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,因此用户可能需要花费两分钟以上的时间来编写内容。

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

<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无形”。因此,我在服务器端得到了missing-input-response。为什么 then 没有在 addEventListener 内触发?

最佳答案

问题在于表单是在异步调用 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>

关于javascript - 验证码3 : How to call execute when user takes the action?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60067216/

相关文章:

vue.js - 如何仅在某些页面上显示验证码图标(VUE reCAPTCHA-v3)?

token - Google reCAPTCHA v3 找不到任何 token

recaptcha-v3 - Google的Recaptcha V3-我应该跟踪分数,还是 "success"为真?

javascript - 我的 javascript 下拉导航菜单显示在 Internet Explorer 7 的内容后面

javascript - 使用 JavaScript 禁用功能

javascript - 如何在 JavaScript 中将转义的 unicode 转换为表情符号?

javascript - 仅在 React 应用程序的特定页面上显示 google Recaptcha V3 floater

html - 如何防止 Google reCAPTCHA (v3) 启用它所附加的按钮

javascript - 使用引导日期选择器进行日期验证

javascript - json/ajax 新手 .. 控制台错误是 Uncaught TypeError : Cannot read property 'length' of undefined