Dmitry Sheiko
Dmitry Sheiko

Reputation: 2192

How to completely clean up Google Analytics cookies (including dynamically set ones like _gali)

Since GDPR we all have cookie preferences and obliged to remove cookies if user withdraw their consent. However, if you have Google Analytics (www.googletagmanager.com/gtag) and clean cookies on a button press event, you can find out after page reload that you still have some GA cookies like _gali and _ga_XXXXXX. So, the question is how to kill these?

Upvotes: 2

Views: 817

Answers (1)

Dmitry Sheiko
Dmitry Sheiko

Reputation: 2192

Apparently GA sets some cookies on document unload (or beforeunload) event. So if you clean up on unload event it works then:

function removeAllCookies() {
    document.cookie.split( ";" ).forEach( cookie => {
        const [ name ] = cookie.split( "=" );
        document.cookie = name + `=; path=/; domain=.YOUR-DOMAIN.com;expires=Thu, 01 Jan 1970 00:00:00 GMT`;
        document.cookie = name + "=; path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    });
}

window.addEventListener("unload", () => removeAllCookies() ); 

Upvotes: 1

Related Questions