[Tutorial] Add reCaptcha v2 to Web Forms

  1. Create a reCaptcha v2 (Click here)
  2. Copy the Site Key
  3. Edit the doctype(or customize it) and add a field captcha_html_wrapper of type HTML to it. You can hide it.
  4. Go to your web form and add this field to it as well.
  5. Now add the following script to client script section of your web form:
frappe.require("https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&type=api.js")

let el = document.querySelector('[data-fieldname="captcha_html_wrapper"]');
window.onloadCallback = function() {
	captcha = grecaptcha.render(el, {
		'sitekey' : '' // Add your site key here.
	});
}

frappe.web_form.after_load = () => {
    frappe.web_form.set_df_property('captcha_html_wrapper', 'hidden', 0);
}

frappe.web_form.validate = () => {
	if (!grecaptcha.getResponse(captcha)) {
	    frappe.throw("Please complete the captcha");
    } else {
        frappe.web_form.doc['captcha_html_wrapper'] = '';
        return true;
    }
}

And that’s it, you have a reCaptcha enabled web form! :slight_smile:

Special thanks to Shivam Mishra @scmmishra

20 Likes

Many thanks for the tutorial ! It is really usefull !
I would like to add some details: be careful to add a server-side verification, otherwise, it is super easy to bypass a only-client-side Captcha by disabling javascript, or by sending raw requet to the server (with Burp for example).

Here is an example of server-side verification with python: reactjs - How to validate a ReCaptcha response server side with Python? - Stack Overflow

Regards

2 Likes