📅  最后修改于: 2023-12-03 15:31:37.473000             🧑  作者: Mango
reCAPTCHA is a free service provided by Google to protect websites from spam and abuse. It can be easily integrated with web applications using JavaScript and HTML.
To use reCAPTCHA, you need to have a Google account and register your website, which will generate a site key and a secret key. You can then add the reCAPTCHA widget to your HTML form.
<html>
<head>
<title>reCAPTCHA Example</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="submit-form" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<div class="g-recaptcha" data-sitekey="SITE_KEY"></div><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Make sure to replace SITE_KEY
with your own site key. When the form is submitted, the reCAPTCHA response token will be sent along with the form data. You can verify the token on the server side using the reCAPTCHA API.
const fetch = require('node-fetch');
const secret = 'SECRET_KEY';
const response = req.body['g-recaptcha-response'];
const remoteip = req.ip;
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret}&response=${response}&remoteip=${remoteip}`;
fetch(url)
.then(res => res.json())
.then(json => {
if (json.success) {
// reCAPTCHA verified
}
});
By verifying the reCAPTCHA response, you can ensure that the form submission is coming from a human user, not a spam bot.
reCAPTCHA offers additional options such as customizing the theme, language, and size of the widget. You can also use invisible reCAPTCHA, which automatically detects if the user is human or bot without requiring them to solve a puzzle.
<div class="g-recaptcha" data-sitekey="SITE_KEY" data-size="invisible"></div>
<button type="submit" onclick="submitForm()">Submit</button>
<script>
function submitForm() {
grecaptcha.execute();
}
function onCaptchaSubmit(token) {
document.getElementById('captcha').value = token;
document.getElementById('form').submit();
}
const siteKey = 'SITE_KEY';
grecaptcha.ready(() => {
grecaptcha.execute(siteKey, { action: 'submit_form' }).then(onCaptchaSubmit);
});
</script>
When using invisible reCAPTCHA, you need to manually trigger the verification by calling grecaptcha.execute()
. Once the verification is complete, the onCaptchaSubmit()
function will be called with the reCAPTCHA response token, which can then be submitted along with the form data.
reCAPTCHA is a powerful tool for protecting your website from spam and abuse. With a few lines of JavaScript and HTML, you can easily integrate reCAPTCHA with your web application and ensure that form submissions are coming from real users.