我正在使用Recaptcha 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')
时,后端没有收到令牌并将用户返回到表单页面并出现验证错误(如果令牌不是,我会阻止发送数据)当下)。
我无法弄清楚如何阻止表单首先提交,直到令牌加载。
所以类似于:
如果用户单击“提交”并且尚未加载令牌,请执行一些加载动画并等待令牌然后提交,如果在用户单击“提交”时存在令牌,则只允许提交表单。
只要未将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>