阻止表单提交,直到recapcha v3完成加载

时间:2019-04-14 08:37:30

标签: javascript jquery recaptcha

我正在使用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')时,后端没有收到令牌,并且将用户返回到带有验证错误的表单页面(我防止数据来自如果令牌不存在则发送)。

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

类似这样:

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

1 个答案:

答案 0 :(得分:0)

只要没有将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>