在 recaptcha v3 完成加载之前阻止表单提交

Prevent form submit until recapcha v3 finished loading

我正在使用 Recapcha V3 在带有令牌的表单中插入隐藏输入。提交表单后,我在后端检查令牌并采取相应措施。

<script src='https://www.google.com/recaptcha/api.js?render={{config("recaptcha.key")}}'></script>
<script>
grecaptcha.ready(function () {
    grecaptcha.execute('{{config("recaptcha.key")}}', {action:  '{{$action}}'}).then(function (token) {
        $('<input />').attr('type', 'hidden')
                .attr('name', 'recaptcha')
                .attr('value', token)
                .appendTo('form');
    });
});
</script>

问题是当用户提交表单的速度太快而输入尚未完成时 appendTo('form'),后端没有收到令牌并且 returns 用户返回表单页面进行验证错误(如果令牌不存在,我会阻止发送数据)。

在加载令牌之前,我不知道如何首先阻止表单提交。

所以像这样:

如果用户单击提交但令牌尚未加载,则执行一些加载动画并等待令牌然后提交,如果用户单击提交时令牌存在,则允许提交表单。

只要 reCAPTCHA 令牌未插入表单,您就需要阻止提交表单。您可以通过使用全局变量来实现此目的,该变量在加载 reCAPTCHA 之后设置并在提交表单之前进行检查:

<script src='https://www.google.com/recaptcha/api.js?render={{config("recaptcha.key")}}'></script>
<script>
// Whether the reCAPTCHA token is loaded into the form
var recaptchaLoaded = false;
// Whether the user already attempted submitting the form
var attemptedSubmit = false;

grecaptcha.ready(function () {
    grecaptcha.execute('{{config("recaptcha.key")}}', {action:  '{{$action}}'}).then(function (token) {
        $('<input />').attr('type', 'hidden')
                .attr('name', 'recaptcha')
                .attr('value', token)
                .appendTo('form');

        window.recaptchaLoaded = true;
        if(window.attemptedSubmit) {
            // As the user already attempted a submit,
            // trigger the "submit" mechanism

            // Note that this doesn't trigger the JS "submit" event
            $("#form").submit();
        }
    });
});

// Add an event listener for "submit"
$("#form").submit(function(event) {
    window.attemptedSubmit = true;
    if(!window.recaptchaLoaded) {
        // The reCAPTCHA token has not been inserted
        // Prevent submission of the form
        event.preventDefault();

        // Your button animation logic here...
    }
});
</script>