andrewlimaza / caldera-forms-anti-spam

Caldera Forms Anti Spam WordPress plugin. This adds Google's reCAPTCHA field to your Caldera Form.
https://wordpress.org/plugins/cf-anti-spam/
25 stars 16 forks source link

Added support for conditional show with lazy loading #18

Closed martin-braun closed 4 years ago

martin-braun commented 4 years ago

This modification will ensure external scripts are not loaded unless the captcha is shown by the Caldera Form. This allows to ask the user for consent before loading any external scripts and the captcha, eventually.

Solves #17 and #1.

martin-braun commented 4 years ago

2020-01-28 01 15 29

A GIF showing the result. I also broadly tested it with two separate captchas, but it might need more testing for several more cases, I think.

Some more background about my implementation

This targets privacy concerning situations. I want the user to give consent before I load third party scripts, obviously, so using wp_enqueue_script() is not possible. Instead I load the script in a script block before each field. To prevent reloading of the captcha script when multiple captchas are used on the website, I use a variable in window to remember, if I already load the script or not. As soon as it has load I set it back to false in cf_recaptcha_is_ready() which will be re-declared for each field, anyways.

Caldera Forms embeds hidden fields within script tags, so any hidden captchas will not be changed by the Google scripts, because they are not found. As soon as the user decides to show one captcha using the condition feature of Caldera Forms, my opening function will remove the content of all captchas and reload the recaptcha script from Google.

I don't think this is the cleanest way and it surely would reset all captchas on the page, so it's not compatible with all possible variations. For instance, showing a 2nd captcha after confirming the first would reset the first, but this is an exceptional case, anyways. That it reloads the script from Google when hiding and showing a captcha is also not perfect, but grecaptcha.reset() or grecaptcha.render() fails and there is no endpoint to re-initialize the captchas, fully, as far as I am concerned.

Also I have not tested how the script reacts when the "hide" or "disable" condition is used, only the "show" condition, as only this makes sense in terms of respecting the privacy of the user. Due to the fact that the previous version didn't support Caldera conditions at all, I think this is a valuable improvement to this plugin.

Please test it nonetheless, I'm experienced in programming, but not in WP / Caldera Forms programming.

Thanks!

andrewlimaza commented 4 years ago

Thanks for this contribution, I've pulled it into the dev branch and will run some tests and include it in a release.

I'll be sure to mention you in the changelog. Thanks so much! :)