ReCaptcha3:当用户执行操作时如何调用 execute?



当像这样包含 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>

但是,在文档中,我发现了以下注释:

注意:reCAPTCHA 令牌会在两分钟后过期。如果要使用 reCAPTCHA 保护操作,请确保在用户执行操作时调用 execute。

由于我在联系表单上使用 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>

现在"嗨"被弹出,但"我是隐形的"不会出现。因此,我在服务器端得到了一个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>

最新更新