laurence keith albano
laurence keith albano

Reputation: 1482

How to keep a cookie value when user visit other pages?

I want to maintain a cookie that is set to not to disappear when a user visit other pages. The situation in my code is that it gets a parameter of the page location and saves it into the / path.

Here's my code:

window.onload = function() {
    try {
        var url_string = (window.location.href).toLowerCase();
        var url = new URL(url_string);
        // Get gclid,token or fbclid parameters
        var gclid = url.searchParams.get("gclid");
        var token = url.searchParams.get("token");
        var fbclid = url.searchParams.get("fbclid");

        // token expires in 6 hours
        document.cookie = `gclid=${gclid}; max-age=21600` + ";path=/";
        document.cookie = `token=${token}; max-age=21600` + ";path=/";
        document.cookie = `fbclid=${fbclid}; max-age=21600` + ";path=/";

    } catch (err) {
        console.log("Issues with Parsing URL Parameter's - " + err);
    }
}

Example:

www.test.com/contact?gclid=123   // saves the cookie value

When going to other pages www.test.com/about it also sets a value to null because the cookie is coming from the url parameters.

the gclid=123 is stored in a cookie in the path /. But when I go to other pages like wwww.test.com/about

the gclid cookie will be equal/set to null.

The situation here in my code is that everytime the user visits a pages the url.searchParams searches for the desired parameter and if it does found those parameter the cookie will be sit to null.

How do I keep the previous value of the cookie gclid if the new gclid contains a null value in my page? And updates the gclid if it does not contains a null value.

Upvotes: 1

Views: 234

Answers (1)

uingtea
uingtea

Reputation: 6524

just check if the parameter is exist

window.onload = function () {
  try {
    var url_string = window.location.href.toLowerCase();
    var url = new URL(url_string);
    ['gclid', 'token', 'fbclid'].forEach(function (key) {
      var value = url.searchParams.get(key);
      if (value) {
        document.cookie = `${key}=${value}; max-age=21600` + ';path=/';
      }
    });
  } catch (err) {
    console.log("Issues with Parsing URL Parameter's - " + err);
  }
}; 

Upvotes: 2

Related Questions