grecaptcha.execute之后如何等待用户完成任务? reCAPTCHA v2不可见

问题描述

我想建立自己的网站, 使用reCAPTCHA。但是,我不知道在grecaptcha.execute()之后如何等待用户完成任务。因为现在链接被直接调用而不传递任务。 其余的我使用标准的Google脚本 https://developers.google.com/recaptcha/docs/invisible 这是reCAPTCHA v2不可见的。

我对答案很满意。

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
     <script>
       function onSubmit(token) {
         grecaptcha.execute().then(var vslg = document.getElementById("vslg").value;
         window.location.replace("url");
       }
     </script>
  </head>
  <body>
    <a class="button"></a>
    <div class="topBar">
    </div>
    <div class="underTopBar">
            <form action="JavaScript:onSubmit()" class="flex-itemform form" method="POST" id="formV">
                <table>
                    <tr>
                        <td>
                            <div>
                                <input type="text"  id="vslg" required>
                            </div>
                        </td>
                        <td>
                            <div>
                                <div class="g-recaptcha"
                                  data-sitekey="..."
                                  data-callback="onSubmit"
                                  data-size="invisible">
                                </div>
                                <input type="submit" class="buttonDesign" value="Senden">
                            </div>
                        </td>
                    <tr>
                </table>
        </form>
    </div>  

解决方法

以下代码可以做到这一点:

  1. <button class="g-recaptcha"...Automatically bind the challenge to a button。单击按钮时,它将自动触发不可见的重新捕获。
  2. 重新验证完成后,它将添加一个名为g-recaptcha-response的隐藏字段,其中包含令牌,然后运行onSubmit回调以提交表单。
  <head>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
     <script>
       function onSubmit() {
         document.getElementById("formV").submit();
       }
     </script>
  </head>
  <body>
    <a class="button"></a>
    <div class="topBar">
    </div>
    <div class="underTopBar">
            <form class="flex-itemform form" method="POST" id="formV">
                <table>
                    <tr>
                        <td>
                            <div>
                                <button 
                                  class="g-recaptcha buttonDesign"
                                  data-sitekey="..."
                                  data-callback="onSubmit"
                                  data-size="invisible">Senden</button>
                            </div>
                        </td>
                    <tr>
                </table>
        </form>
    </div>  

重要:您仍然需要验证令牌g-recaptcha-response服务器端。参见Verifying the user's response。在不验证令牌的情况下,将Recaptcha添加到前端并不会阻止任何人提交表单。