我在网页上的 Ajax (Javascript / PHP) 表单中添加了 Google 不可见的 recaptcha(请参阅下面客户端的 html + js)。一切正常,除了谷歌不可见的 Recaptcha 经常在网页加载和表单提交时启动图像挑战。
这很烦人,因为包含这个提交表格的页面是网站的主页(实际上是一个协会的请愿签名网站)。
这导致用户甚至在从网站获取主要信息并决定签署或不签署请愿书之前就可以看到图像挑战的问题。这是一种糟糕的用户体验。
有没有办法防止这种行为。以这样的方式配置 Google Recaptcha 在用户点击提交按钮之前不具有挑战性?
非常感谢您的宝贵帮助:o)!
洛朗
Javascript代码:
window.onScriptLoad = function () {
var htmlEl = document.querySelector('.g-recaptcha');
var captchaOptions = {
'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'size': 'invisible',
'badge': 'inline',
callback: window.onUserVerified
};
var inheritFromDataAttr = true;
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
console.log('recaptchaId=', recaptchaId);
window.grecaptcha.execute(recaptchaId);
};
window.onUserVerified = function (token) {
console.log('token=', token);
};
function onSubmitBtnClick () {
var token = window.grecaptcha.getResponse(recaptchaId);
console.log('token=', token);
if (!token) {
window.grecaptcha.execute(recaptchaId);
return;
}
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data : {
'lastname' : $("#lastnameField").val(),
'firstname' : $("#firstnameField").val(),
'city' : $("#cityField").val(),
'postalCode' : $("#postalcodeField").val(),
'g-recaptcha-response' : token
},
success:function(data) {
// informs user that form has been submitted
// and processed
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
HTML 代码:
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad" async defer></script>
<script type="text/javascript" src="js/petition.js"></script>
...
</head>
<body>
<form id="petitionForm" onsubmit="return false;">
<input id="lastnameField" type="text" name="lastname" placeholder="Lastname" required value="Doe">
<input id="firstnameField" type="text" name="firstname" placeholder="Firstname" required value="John">
<input id="postalcodeField" type="text" name="postalCode" placeholder="Postal Code" required value="ABCDEF">
<input id="cityField" type="text" name="city" placeholder="City" value="Oslo">
....
<input type="submit" name="login" class="g-2" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxx" id="signButton" data-callback='' value="Signer" onclick="onSubmitBtnClick();">
<div class="g-recaptcha" id="recaptchaElement" style="align-content: center"></div>
</form>
...
</body>
</html>