- Create a reCaptcha v2 (Click here)
- Copy the
Site Key
- Edit the doctype(or customize it) and add a field
captcha_html_wrapper
of typeHTML
to it. You can hide it. - Go to your web form and add this field to it as well.
- 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!
Special thanks to Shivam Mishra @scmmishra