Search code examples
javascriptcookiesurl-parameters

How to check paramaters stored as cookie in if-else condition?


I want to check cookie values stored as parameters in if-else condition. I added a variable params to be able to pass it into a new url for those cookies using the XMLHttpRequest() later. But it seems that the problem in my if-else condition is that it only pulls the first parameter entered by the user.

Example:

1.) When user adds a parameter for the first time like ?gclid=sample in the url. It will alert that parameter.

2.) But when user enters another url parameter the second time like ?cjevent=3212 it will still return the first parameter entered by the user.

Javascript

<script>
window.onload = function() {
try {
    var url_string = (window.location.href).toLowerCase();
    var url = new URL(url_string);

    // check parameters if exists
    ['gclid', 'token', 'fbclid', 'cjevent'].forEach(function (key) {
        var value = url.searchParams.get(key);
        if (value) {
            //token expires in 6 hours
            document.cookie = `${key}=${value}; max-age=21600` + ';path=/';
        }
    });

    const getCookieValue = (name) => (
        document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
    )
    var params = '';

    // pass parameters if gclid, token, fbclid, cjevent
    if(getCookieValue('gclid')) { params = 'gclid=' + getCookieValue('gclid');}
    else if (getCookieValue('token')) { params = 'token=' + getCookieValue('token');}
    else if (getCookieValue('fbclid')) { params = 'fbclid=' + getCookieValue('fbclid');}
    else if (getCookieValue('cjevent')) { params = 'cjevent=' + getCookieValue('cjevent');}

    alert(params);

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

}
</script>

I believe I need to refactor my condition in here.

if(getCookieValue('gclid')) { params = 'gclid=' + getCookieValue('gclid');}
    else if (getCookieValue('token')) { params = 'token=' + getCookieValue('token');}
    else if (getCookieValue('fbclid')) { params = 'fbclid=' + getCookieValue('fbclid');}
    else if (getCookieValue('cjevent')) { params = 'cjevent=' + getCookieValue('cjevent');}

Is there anyway to get the latest parameter entered by the user and check it using alert() function?


Solution

  • Yes, you have no need this conditions. As I understand you, all cookies can be available at the same time and you need their latest actual values. So, we can modify you code this way:

    window.onload = function() {
      try {
        const url_string = (window.location.href).toLowerCase();
        const url = new URL(url_string);
        const paramsArray = ['gclid', 'token', 'fbclid', 'cjevent'];
        const getCookieValue = (name) =>
          document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || '';
    
        // One loop for both: write and read cookies.
        paramsArray.forEach(function (key) {
          const value = url.searchParams.get(key);
    
          if (value) {
            const currentCookieValue = getCookieValue(key);
            const cookieDoesNotExist = !currentCookieValue;
            const valuesAreNotEqual = currentCookieValue !== value;
    
            //token expires in 6 hours
            document.cookie = `${key}=${value}; max-age=21600;path=/`;
    
            if (cookieDoesNotExist || valuesAreNotEqual) {
              const params = `${key} = ${getCookieValue(key)}`;
              alert(params);
            }
          }
        });
      } catch (err) {
        console.log(`Issues with Parsing URL Parameter's - ${err}`);
      }
    }