Run Script after a cookie is set without reloading the page

I am currently learning JavaScript and am currently trying cookies. I'm just trying to build a cookie banner with opt-in capabilities so Analytics should not run until after the cookie is set.

So I have the following code:

if (getCookie ("cookieTracking") === "1") {
  console.log ("Run Script");
}

My Analytics program should not run on the first pageview. That works as far as I want. The page is loading and does not run the script because the cookie was not set. As soon as the user activates the tracking in the cookie banner, the script will also be loaded.

Now for my problem: The fact that the page is now loaded, the browser does not execute the IF command again. Accordingly, the analytics code remains unexecuted. Only when I reload the page will the IF command be true and start the script.

That's all as far as logical. But this results in a distortion of Analytics data because the first visit is not counted. How can I re-execute the IF command after the cookie is set?

PS: I signed up for Stackoverflow for the first time today, although I've been using it for a long time. I hope I can do my part and help you too!

Upvotes: 1

Views: 2034

Answers (1)

Mac_W
Mac_W

Reputation: 2987

I believe you could you a Promise and do something like below:

    var cookie = new Promise((res, rej) => {
      // Possibly a function call below
      document.cookie = "test=1"; 
      // just simplified check
      document.cookie.search(/test=1/) ? res() : rej()  
    })
    // call promise to check if it's fullfilled or rejected
    cookie.then(() => console.log('set')).catch((err) => console.log('failed'))


What the above does is you create a new promise which sets a cookie. After that you search for cookies and if it was set or equals 1 you resolve the promise otherwise you reject it.

Then you call the cookie and using then and catch check if the cookie is present.

Upvotes: 1

Related Questions