Skip to content

Instantly share code, notes, and snippets.

@jiankaiwang
Last active June 7, 2024 10:27
Show Gist options
  • Save jiankaiwang/dc5690318bd035232a8ac9294bc2af29 to your computer and use it in GitHub Desktop.
Save jiankaiwang/dc5690318bd035232a8ac9294bc2af29 to your computer and use it in GitHub Desktop.
the example to use recaptcha in javascript
<!--
Description: The following is the example code to use recaptcha.
Notice: The function backend_API_challenge is the concept and you should implement it on the backend.
Especially, you must keep your secret key in private all the time.
Flow:
1. Click the submit button.
2. On the console, execute backend_API_challenge function.
-->
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js' async defer></script>
</head>
<body>
<form>
<input type="text"></input>
<div class="g-recaptcha" data-sitekey="(your-site-key)"></div>
<input type="button" onclick="checkRecaptcha();" value="submit"></input>
</form>
<script>
function checkRecaptcha() {
var response = grecaptcha.getResponse();
if(response.length == 0) {
//reCaptcha not verified
alert("no pass");
}
else {
//reCaptch verified
alert("pass");
}
}
// implement on the backend
function backend_API_challenge() {
var response = grecaptcha.getResponse();
$.ajax({
type: "POST",
url: 'https://www.google.com/recaptcha/api/siteverify',
data: {"secret" : "(your-secret-key)", "response" : response, "remoteip":"localhost"},
contentType: 'application/x-www-form-urlencoded',
success: function(data) { console.log(data); }
});
}
</script>
</body>
</html>
@YSHgroup
Copy link

YSHgroup commented Jun 3, 2024

It's great, do I have to use the Gmail to get my own site key for Recaptcha?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment