ReCaptcha3: How to call execute when user takes the action?

被刻印的时光 ゝ 提交于 2020-05-17 07:16:07

问题


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:

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.

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>

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?


回答1:


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>


来源:https://stackoverflow.com/questions/60067216/recaptcha3-how-to-call-execute-when-user-takes-the-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!