@damusix/recaptcha
v2.0.0
Published
Implements recaptcha on a website using a simple browser script
Readme
@damusix/recaptcha
A lightweight JavaScript library that simplifies the integration of Google reCAPTCHA into web forms. This package handles the automatic setup of reCAPTCHA callbacks and form submissions, making it easy to implement across multiple forms on your website.
Features
- 🔄 Automatic callback function creation
- 📝 Form submission handling
- 🎯 Multiple form support
- 🛡️ Type-safe implementation
- 🎨 Zero dependencies
- 🚀 Simple integration
Installation
To use the Floating Share Button via CDN, include the following script tag in your HTML:
<script src="https://cdn.jsdelivr.net/npm/@damusix/[email protected]/main.js"></script>Usage
- First, add the reCAPTCHA script to your HTML:
<script src="https://www.google.com/recaptcha/api.js?....." async defer></script>- Add the reCAPTCHA button to your form with a data-callback attribute:
<form id="myForm">
<!-- Your form fields -->
<button
class="g-recaptcha"
type="submit"
>
Submit
</button>
</form>- Initialize the handler in your JavaScript:
document.addEventListener('DOMContentLoaded', () => {
HandleRecaptcha.create({
elementSelector: '.g-recaptcha',
recaptchaKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
onToken: ({ token, button, form }) => {
// Handle the token
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'g-recaptcha-response';
input.value = token;
form.appendChild(input);
form.submit();
}
});
});Multiple Forms
You can handle multiple forms by creating multiple instances with different selectors:
document.addEventListener('DOMContentLoaded', () => {
// Handle login form
HandleRecaptcha.create({
buttonSelector: '#login-form .g-recaptcha',
onToken: ({ token, form }) => {
// Handle login form token
}
});
// Handle registration form
HandleRecaptcha.create({
buttonSelector: '#register-form .g-recaptcha',
onToken: ({ token, form }) => {
// Handle registration form token
}
});
});API Reference
HandleRecaptcha.create(options)
Creates a new reCAPTCHA handler instance.
Options
| Option | Type | Required | Description | |--------|------|----------|-------------| | buttonSelector | string | Yes | CSS selector for the reCAPTCHA button | | onToken | function | No | Callback function that receives the token and form context |
onToken Callback
The onToken callback receives an object with the following properties:
token: The reCAPTCHA response tokenbutton: The button element that triggered the reCAPTCHAform: The parent form element
Error Handling
The package includes built-in error handling for common issues:
- Missing button selector
- Invalid selector type
- Missing callback function
- Missing callback attribute on button
License
ISC
