Search code examples
javascriptcookiesgoogle-analyticssession-cookies

How do cookie consent pop-ups work internally?


My project is linked with Google Analytics. Now I would like to create a cookie consent pop-up on my website to comply with EU regulations.

Now I see in the EU regulations that the user can select "allow" or "deny". And then you can anonymize Google Analytics. But how does this work internally in my code?

I don't really know how this all works in code, does anyone have examples?

On the internet you will find a lot about how to create the pop-up, but they never go further on how to code everything internally.


Solution

  • Cookies are files at are stored on your computer that the website can access, 3rd party cookies are cookies that other websites can access too. The most basic way of creating a cookie is by using the browsers local storage. Your allow/deny system can be as simple as a true/false value stored globally, use an if statement to check if cookies are allowed or not every time you get or store a value from local storage.

    Here are some examples.

    // This will store a value/cookie with the id "myKey" and the value "myValue"
    Window.localStorage.setItem("myKey", "myValue");
    
    // You can get the value/cookie you stored earlier by using the values ID, in this case it should return "myValue"
    Window.localStorage.getItem("myKey");
    
    // To delete a value/cookie do this
    Window.localStorage.remove("myKey");
    
    // this is your logic to check if cookies are allowed
    let AreCookiesAllowed = true;
    
    if (AreCookiesAllowed === true)
    {
        // Do things with cookies
        Window.localStorage.setItem("theme", "dark");
    }
    
    

    Reference material can be found here.