代码之家  ›  专栏  ›  技术社区  ›  Adam

ReCaptcha3:当用户执行操作时,如何调用execute?

  •  0
  • Adam  · 技术社区  · 5 年前

    当我像这样包含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 ?

    1 回复  |  直到 5 年前
        1
  •  3
  •   Adam    5 年前

    问题是表单是在异步调用之前提交的 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>