Till now, I was using Google's reCaptcha challenge for spam protection. But now I want…
- User
Till now, I was using Google's reCaptcha challenge for spam protection. But now I want to switch to Cloudflare's Turnstile. Here is my old JavaScript code for reCaptcha handling: /** * Contact form submission */ let forms = document.querySelectorAll('.php-email-form'); let status = document.querySelector('#status');
forms.forEach( function(e) { e.addEventListener('submit', function(event) { event.preventDefault(); let thisForm = this; let action = thisForm.getAttribute('action'); let recaptcha = thisForm.getAttribute('data-recaptcha-site-key'); if (!action) { displayError(thisForm, 'The form action property is not set!') return; } status.querySelector('.loading').classList.add('d-flex'); status.querySelector('.error-message').classList.remove('d-block'); status.querySelector('.sent-message').classList.remove('d-block'); let formData = new FormData( thisForm ); if (recaptcha) { if(typeof grecaptcha !== "undefined" ) { grecaptcha.ready(function() { try { grecaptcha.execute(recaptcha, {action: 'php_email_form_submit'}) .then(token => { formData.set('recaptcha-response', token); php_email_form_submit(thisForm, action, formData); }) } catch(error) { displayError(thisForm, error) } }); } else { displayError(thisForm, 'The reCaptcha javascript API url is not loaded!') } } else { php_email_form_submit(thisForm, action, formData); } }); }); function php_email_form_submit(thisForm, action, formData) { fetch(action, { method: 'POST', body: formData, headers: {'X-Requested-With': 'XMLHttpRequest'} }) .then(response => { if( response.ok ) { return response.text() } else { throw new Error(`${response.status} ${response.statusText} ${response.url}`); } }) .then(data => { status.querySelector('.loading').classList.remove('d-flex'); if (data.trim() == 'OK') { status.querySelector('.sent-message').classList.add('d-block'); thisForm.reset(); } else { throw new Error(data ? data : 'Form submission failed and no error message returned from: ' + action); } }) .catch((error) => { displayError(thisForm, error); }); } function displayError(thisForm, error) { status.querySelector('.loading').classList.remove('d-flex'); status.querySelector('.error-message').innerHTML = error; status.querySelector('.error-message').classList.add('d-block'); }I want you to write similar JavaScript code for Cloudflare's Turnstile, replacing Google's reCaptcha.
- Assistant
Certainly! Below is a revised version of your JavaScript code that replaces Google’s reCAPTCHA with Cloudflare’s Turnstile for spam protection. This implementation assumes you’re using Turnstile’s invisible mode, which operates similarly to reCAPTCHA v3 by programmatically obtaining a token without user interaction.
Overview of Changes:
- Script Inclusion: Replace the reCAPTCHA script with Cloudflare Turnstile’s API script.
- Data Attributes: Update data attributes from
data-recaptcha-site-keytodata-turnstile-site-keyin your HTML forms. - JavaScript Logic: Modify the submission logic to use Turnstile’s token retrieval and handle it similarly to how you handled reCAPTCHA tokens.
Step-by-Step Implementation:
-
Include Cloudflare Turnstile’s API Script
Ensure that you include the Turnstile API script in your HTML, preferably before your custom JavaScript. Replace the reCAPTCHA script with the following:
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script> -
Update Your HTML Forms
Modify your form elements to use
data-turnstile-site-keyinstead ofdata-recaptcha-site-key. For example:<form class="php-email-form" action="/your-action-endpoint" data-turnstile-site-key="your-site-key"> <!-- Your form fields --> <!-- Hidden Turnstile widget (invisible) --> <div class="cf-turnstile-widget" style="display: none;"></div> <!-- Status Messages --> <div id="status"> <div class="loading">Loading...</div> <div class="error-message"></div> <div class="sent-message">Your message has been sent. Thank you!</div> </div> <button type="submit">Send Message</button> </form>Notes:
- The
.cf-turnstile-widgetdiv is a placeholder for the invisible Turnstile widget. It’s hidden by default. - Ensure each form has a unique
.cf-turnstile-widgetif you have multiple forms on the same page.
- The
-
JavaScript Code for Handling Turnstile
Here's the complete JavaScript code adapted for Cloudflare Turnstile:
/** * Contact form submission handling with Cloudflare Turnstile */ // Select all forms with the class 'php-email-form' const forms = document.querySelectorAll('.php-email-form'); const status = document.querySelector('#status'); forms.forEach((form, index) => { form.addEventListener('submit', function(event) { event.preventDefault(); // Prevent the default form submission const action = form.getAttribute('action'); const turnstileSiteKey = form.getAttribute('data-turnstile-site-key'); if (!action) { displayError(form, 'The form action property is not set!'); return; } // Show loading status status.querySelector('.loading').classList.add('d-flex'); status.querySelector('.error-message').classList.remove('d-block'); status.querySelector('.sent-message').classList.remove('d-block'); const formData = new FormData(form); if (turnstileSiteKey) { if (typeof turnstile !== "undefined") { // Generate a unique callback name for each form const callbackName = `turnstileCallback_${index}_${Date.now()}`; // Define the callback function to handle the token window[callbackName] = function(token) { // Append the Turnstile token to the form data formData.set('cf-turnstile-response', token); // Submit the form data via Fetch API php_email_form_submit(form, action, formData); // Clean up the callback to avoid memory leaks delete window[callbackName]; }; // Find or create the Turnstile widget within the form let widget = form.querySelector('.cf-turnstile-widget'); // If the widget is not rendered yet, render it if (!widget.dataset.rendered) { widget.setAttribute('data-sitekey', turnstileSiteKey); widget.setAttribute('data-callback', callbackName); widget.setAttribute('data-size', 'invisible'); // Invisible mode widget.dataset.rendered = 'true'; // Flag to prevent re-rendering // Render the Turnstile widget turnstile.render(widget, { type: 'invisible', callback: callbackName }); } // Execute the Turnstile challenge to obtain the token turnstile.execute(widget); } else { displayError(form, 'The Turnstile JavaScript API is not loaded!'); } } else { // If Turnstile is not configured, submit the form directly php_email_form_submit(form, action, formData); } }); }); /** * Function to submit the form data via Fetch API * @param {HTMLFormElement} form - The form being submitted * @param {string} action - The form action URL * @param {FormData} formData - The form data to send */ function php_email_form_submit(form, action, formData) { fetch(action, { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } }) .then(response => { if (response.ok) { return response.text(); } else { throw new Error(`${response.status} ${response.statusText} ${response.url}`); } }) .then(data => { // Hide loading status status.querySelector('.loading').classList.remove('d-flex'); if (data.trim() === 'OK') { // Show success message and reset the form status.querySelector('.sent-message').classList.add('d-block'); form.reset(); } else { // Handle server-side validation errors throw new Error(data || 'Form submission failed and no error message returned from the server.'); } }) .catch(error => { // Display any errors encountered during submission displayError(form, error); }); } /** * Function to display error messages * @param {HTMLFormElement} form - The form where the error occurred * @param {Error|string} error - The error message to display */ function displayError(form, error) { // Hide loading status status.querySelector('.loading').classList.remove('d-flex'); // Display the error message status.querySelector('.error-message').innerHTML = error; status.querySelector('.error-message').classList.add('d-block'); }Explanation of the JavaScript Code:
-
Form Selection: The script selects all forms with the class
.php-email-formand attaches asubmitevent listener to each. -
Prevent Default Submission: On form submission, the default behavior is prevented to allow for asynchronous handling.
-
Status Handling: It manages the display of loading indicators, error messages, and success messages by manipulating CSS classes.
-
Turnstile Integration:
- Callback Naming: A unique callback function name is generated for each form submission to handle the Turnstile token.
- Rendering the Widget: If the Turnstile widget hasn't been rendered for the form, it’s rendered in invisible mode. This ensures that the widget is only created once per form.
- Executing Turnstile: The
turnstile.execute(widget)function triggers the Turnstile challenge, which upon completion, invokes the specified callback with the token. - Token Handling: Once the token is received, it's appended to the
FormData, and the form is submitted via thefetchAPI.
-
Form Submission: The
php_email_form_submitfunction handles the asynchronous submission of the form data to the server and manages the response, displaying appropriate messages based on the outcome. -
Error Display: Any errors encountered during the process are displayed to the user through the
displayErrorfunction.
-
-
Server-Side Verification
After updating the client-side code, ensure that your server-side logic verifies the Turnstile token (
cf-turnstile-response) to confirm that the submission is legitimate. Refer to Cloudflare’s Turnstile Verification Documentation for detailed instructions on how to perform this verification.
Additional Considerations:
-
Multiple Forms: This implementation supports multiple forms on the same page by generating unique callbacks and ensuring each form has its own hidden Turnstile widget.
-
Styling: Since the Turnstile widget is set to
display: none;, it won’t be visible to users. Ensure that your CSS does not interfere with the.cf-turnstile-widgetelement. -
Graceful Degradation: If Turnstile fails to load or execute, the form submission will still proceed without spam protection. You might want to handle this scenario based on your security requirements.
-
Testing: After implementing, thoroughly test the form submission to ensure that Turnstile tokens are correctly generated, sent to your server, and verified.
By following the above steps, you should be able to smoothly transition from Google’s reCAPTCHA to Cloudflare’s Turnstile for protecting your forms against spam and abuse.