jquery - 如何在前端使用 reCaptcha V3 和 jQuery?
问题描述
以下是我的登录页面的 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
正确。
解决方案
推荐阅读
- java - 导入java.io.*;行不通,怎么办,没办法?
- puppetlabs-aws - 我需要将 aws_session_token 与 puppetlabs-aws 一起使用
- javascript - 具有增量和减量输入的jquery数据表
- scopus - 如何检索查询中每个 Scopus 记录的所有作者
- android - 如何将protobuf添加到flutter/kotlin android项目中
- ruby-on-rails - (Rails 5) LoadError: cannot load such file -- sass ...当部署到 Heroku
- testing - 如何使用 cypress 登录 salesforce?
- mysql - SQL 查询没有返回我想要的东西
- javascript - 如何避免缩进嵌套承诺?
- ios - Swift:如何在不显式使用 CGRect 的情况下为 UIView 或 CALayer 的每个角设置不同的半径?