以下是我的登录页面的 HTML:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="/resources/libraries/jquery/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js?render=<recaptchaSiteKey>"></script>
</head>
<body>
<form id="loginForm">
<table>
<tr>
<td>User:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
<input id="recaptchaSiteKey" type="hidden" value="<recaptchaSiteKey>" />
<script type="text/javascript">
$(document).ready(() => {
$('#loginForm').submit((event) => {
event.preventDefault();
const siteKey = $('#recaptchaSiteKey').val();
grecaptcha.ready(() => {
grecaptcha
.execute(siteKey, {
action: 'login'
})
.then((token) => {
$('#loginForm').prepend(`<input type="hidden" name="g-recaptcha-response" value="${token}" />`);
const submittableForm = $(`<form action="/login" method="POST" />`);
$('#loginForm *').filter(':input')
.each((index, element) => {
const jqElement = $(element);
const name = jqElement.attr('name');
const value = jqElement.val();
if (name && value) {
submittableForm.append(`<input type="hidden" name="${name}" value="${value}" />`)
}
});
$(document.body).append(submittableForm);
$(submittableForm).submit();
});
});
});
});
</script>
</body>
</html>
在reCaptcha V3 - Frontend integration的文档中,提到:
<script src="https://www.google.com/recaptcha/api.js?render=_reCAPTCHA_site_key"></script> <script> grecaptcha.ready(function() { grecaptcha.execute('_reCAPTCHA_site_key_', {action: 'homepage'}).then(function(token) { ... }); }); </script>
- 使用您的站点密钥加载 JavaScript api
- 在操作或页面加载时调用 grecaptcha.execute
- 将令牌与验证请求一起发送到您的后端
我想知道我是否使用grecaptcha.execute
正确。