我集成了新的隐藏 reCAPTCHA (v2) 框架,该框架默认使用click
提交按钮的事件验证用户。但是这个事件是在内置的 HTML5 表单验证之前触发的。我正在寻找一种按预期顺序制作的方法:首先是表单验证,然后是 reCAPTCHA。
7 回答
由于新的 v2grecaptcha
方法,您必须以编程方式执行此操作:grecaptcha.execute()
这样 recaptcha 不会替换按钮的默认单击事件,这会阻止默认的 HTML5 表单验证。
事件路径为:
- 提交按钮点击事件:浏览器内置表单验证
- 表单提交事件:调用
grecaptcha.execute()
- reCAPTCHA 回调:提交表单
$('#form-contact').submit(function (event) {
event.preventDefault();
grecaptcha.reset();
grecaptcha.execute();
});
function formSubmit(response) {
// submit the form which now includes a g-recaptcha-response input
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<form action="?">
<div class="g-recaptcha"
data-sitekey="your-key"
data-size="invisible"
data-callback="formSubmit">
</div>
<button type="submit">Submit</button>
</form>
这是我获得 HTML5 验证 + Invisible recaptcha 的解决方案:
HTML:
<form id="my-form">
<!-- Your form fields ... -->
<div class="g-recaptcha"
data-sitekey="..."
data-callback="submitMyForm"
data-size="invisible">
</div>
<button type="submit">Submit</button>
</form>
JS:
var myForm = $('my-form');
function submitMyForm () {
myForm.trigger('submit', [true]);
}
$(function () {
myForm.on('submit', function (e, skipRecaptcha) {
if(skipRecaptcha) {
return;
}
e.preventDefault();
grecaptcha.execute();
});
})
嗨,这里有一个可行的解决方案。使用隐形 Recaptcha。
jQuery(document).ready(function() {
var commentform = jQuery("#commentform");
commentform.on("click", "#submit-comment", function(e) {
if(commentform[0].checkValidity()) {
e.preventDefault();
grecaptcha.execute();
}
});
});
function submitCommentForm(data) {
document.getElementById("commentform").submit();
}
<form action="blaba.php" method="post" id="commentform" class="comment-form">
<div class="form-submit">
<div data-callback="submitCommentForm" data-sitekey="yourkey" class="g-recaptcha" data-size="invisible">
<button id="submit-comment">Leave a comment</button>
</div>
</form>
我遇到了这个问题,因为默认方法似乎覆盖了 html5 表单验证。我还希望所有代码都是通用的,而不是硬编码任何函数/元素名称。最后,我使用 v3 api 想出了以下代码 -
HTML
<form method="post" action="?" class="ui-recaptcha" name="my_form_name">
...
<input type="submit" value="Submit">
</form>
<script src="//www.google.com/recaptcha/api.js?render={key}" async defer></script>
Javascript(我正在使用 jQuery,但很容易适应 vanilla js)
$('.ui-recaptcha').submit(e => {
var form = e.target;
if( $(form).data('recaptcha-done') )
return;
e.preventDefault();
grecaptcha.execute('{key}', {'action': $(form).attr('name')}).then(token => {
$(form).append($('<input>').attr({'type': 'hidden', 'name': 'g-recaptcha-response', 'value': token}));
$(form).data('recaptcha-done', true);
$(form).submit();
});
});
我发现只是像上面的一些例子那样调用给我造成了一个循环,当recaptcha 处理程序在事件submit
上运行时,这将是有意义的。submit
这将为任何表单运行 recaptcha ui-recaptcha
,将 formname
属性作为可以在 reCaptcha 控制台中看到的操作传递,然后将令牌插入到表单中。一旦运行,它会在表单上设置一个数据属性,因此对提交的递归调用不会尝试再次运行 recaptcha。
这是我的解决方案。
- 使用 reCaptcha v3(不可见)文档
- 使用原生 HTML5 表单验证
- 使用纯 JS
- 使用标准 POST 处理(可以修改为 AJAX)
根据需要添加尽可能多的表单,只需更改两个位置的“UNIQUE_FORM_ID”,并更新表单的 POST_URL。确保在“RECAPTCHA_SITE_KEY”的位置使用自己的密钥。
<form id="UNIQUE_FORM_ID" method="post" action="POST_URL">
<!-- ** Notice ** this hidden input field that will later send our g-recaptcha token back to our server -->
<input type="hidden" name="g-recaptcha-response" value="">
<!-- Add other hidden nonce fields -->
<!-- Required field -->
<input name="fullname" type="text" placeholder="Full Name" required>
<!-- Submit button -->
<!-- ** Notice ** the 'form' attribute; using SAME value as it's parent's form id, above. -->
<!-- ** Notice ** the 'onclick' attribute; be sure to pass event -->
<button type="submit" form="UNIQUE_FORM_ID" onclick="formSubmitBtn(event)">Send</button>
</form>
<!-- Only add scripts once -->
<!-- ** Notice ** to manually call grecaptcha, our site key must be included when loading api.js using the 'render' query param -->
<script src="https://www.google.com/recaptcha/api.js?render=RECAPTCHA_SITE_KEY"></script>
<script>
/**
* Handles form submissions for Google recaptcha v3.
* Allows for HTML5 form validation to complete before processing.
*/
function formSubmitBtn($event) {
/**
* Checks the validity of the form.
* Return if invalid; HTML5 validation errors should display.
*/
if (!$event.target.form.checkValidity()) {
return;
}
/**
* Form is client-side valid; taking over the remainder of processing.
*/
$event.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute("RECAPTCHA_SITE_KEY", { action: 'submit' }).then(function(token) {
/**
* Adds the token g-recaptcha-response token to our hidden form element.
* ** Notice ** we our referencing the specific form's input element by name here (do not use IDs).
*/
$event.target.form.elements['g-recaptcha-response'].value = token;
/**
* Use the form API directly to submit the form.
*/
$event.target.form.submit();
});
});
}
</script>
我想要相同的行为,但使用新的 recaptcha,即隐形的。在查看了一些代码并测试了一些东西之后,我进入了这个。主要区别在于这也使用了默认的浏览器验证:
var contact_form;
$(function() {
contact_form = $('#contact-form');
contact_form.submit(function (event) {
if ( ! contact_form.data('passed')) {
event.preventDefault();
grecaptcha.execute();
}
});
});
function sendContactForm(token) {
contact_form.data('passed', true);
contact_form.submit();
}
它基本上将jquery表单对象存储在一个全局变量中,包括它sendContactForm
用作回调,但是当被recaptcha调用时,它设置了一个名为的数据变量passed
,这使得表单不会被阻止。这与 recaptcha 通常会做的行为完全相同,但在这种情况下。
更新:重新查看我的代码提醒我,它可能需要一种方法来恢复false
在 grecaptcha 执行后传递给的数据。考虑一下,如果你要实现这个。
let siteKey = "...";
$("form").submit(function (eventObj) {
var myForm = this;
eventObj.preventDefault();
grecaptcha.execute( siteKey, {
action: "submit"
})
.then(function (token) {
$('<input />').attr('type', 'hidden')
.attr('name', "g_recaptcha_response")
.attr('value', token)
.appendTo(myForm);
myForm.submit();
});
});
这将执行 recapcha,等待响应,在浏览器尝试提交时将隐藏属性 g_recaptcha_response 添加到任何表单,然后实际提交。您需要全局变量 siteKey