Change cookie banner to use javascript events rather than a filter
Hey Ben,
I've been working on cookie consents today. Trying to unstack my brain and dipped into Toolbelt for inspiration.
My current problem is that I can get as far as getting a cookie set, but like you I'm then filtering the analytics code into the HTML at the back-end.
This was giving me problems with page caching. Unless you're doing fragment caching (which is a bit tricky in most hosting setups) the page is cached either with or without the analytics code. Not ideal.
The simplest next step is to ALWAYS output the JS code but to only execute it if the cookie is set.
So you do something like:
if (document.cookie.indexOf("toolbelt_cookies_accepted=") >= 0) {
// Analytics code
}
I know this issue is about using events, but it seemed related enough.
It would be nice if you would do:
if (document.cookie.indexOf("toolbelt_cookies_accepted=") >= 0) {
runAnalytics();
}
document.addEventListener('toolbeltsAcceptCookiesEvent', runAnalytics);
and catch the accepting event, but I'm not sure all analytics scripts will fit inside a functions.
I'm happy with the former approach and a page-reload on accept (does Toolbelt do this?)
Happy to try and PR this if you want me to. I know it's not as privacy-aware as you like but I WOULD like this to work with Google Analytics for my clients that need it.
Cheers!
Thanks for the feedback!
Just to confirm - have you looked at the Toolbelt docs? I put together something that I think does what you want - in a not very elegant way (which is why I want to switch to js events). https://github.com/BinaryMoon/wp-toolbelt/wiki/Cookie-Banner#google-analytics-tracking
I've just added some extra info to the docs to try to make it clearer how it works/ what it does. So if you have looked at it then it may be a bit different now.
In essence though - if you use the Google Analytics code example detailed on the docs page then that code will be executed when the accept button is pressed, and on page load for any user who has accepted the cookies. Everything in Toolbelt is designed with page caching in mind so it should work ok.
I used to use it on my personal site before I swapped over to Fathom and I think it worked as expected.
I've just added some events to Toolbelt that you can hook into if you want but I haven't swapped over the old method (back compat).
You can see the dev code for the cookie banner here: https://github.com/BinaryMoon/wp-toolbelt/tree/dev/modules/cookie-banner
If any of it isn't clear let me know and I'll add more comments :)