我成功地让 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我发现以下注释:
Note: reCAPTCHA tokens expire after two minutes. If you're protecting an action with reCAPTCHA, make sure to call execute when the user takes the action.
由于我在联系表单上使用 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>
现在会提示“Hi”,但不会显示“Iam无形”。因此,我在服务器端得到了missing-input-response
。为什么 then
没有在 addEventListener
内触发?
最佳答案
问题在于表单是在异步调用 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>
关于javascript - 验证码3 : How to call execute when user takes the action?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60067216/