如何在 if-else 条件下检查存储为 cookie 的参数?

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

我想检查在 if-else 条件下作为参数存储的 cookie 值。我添加了一个变量 params,以便稍后使用 XMLHttpRequest() 将其传递到新的 url 中。但是好像我的if-else条件的问题是只拉取了用户输入的第一个参数。

示例:

1.) 当用户第一次在url中添加参数如?gclid=sample时。它将提醒该参数。

2.) 但是当用户第二次输入另一个 url 参数时 ?cjevent=3212 它仍然会 return 用户输入的第一个参数。

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>

我认为我需要在这里重构我的条件。

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()函数检查?

是的,你不需要这个条件。据我了解,所有 cookie 可以同时可用,您需要它们的最新实际值。所以,我们可以这样修改你的代码:

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}`);
  }
}