基于 URL 参数设置 Javascript Cookie

Set a Javascript Cookie based on URL Params

本文关键字:Javascript Cookie 设置 参数 URL 基于      更新时间:2023-09-26

我很好奇是否有人可以帮助一个非常新的Javascript用户根据特定的URL参数来理解如何设置cookie。我看到这篇文章涵盖了使用 JavaScript 从 URL 中提取数据:如何在 JavaScript 中获取查询字符串值?

但是我不知道如何将这些信息提取到cookie中,以在整个网站上的用户会话中存储信息。

我想获取 3 个主要 URL 参数:utm_sourceutm_mediumutm_campaign

然后使用 Javascript 将它们存储在 Google Tag Manager 中的 cookie 中。

我无法解决这个问题。任何帮助将不胜感激。抱歉,我没有太多代码可供参考,但是我已经进行了几个小时的实验(并失败了(。

非常感谢您对此的任何见解。

欢呼蜜蜂花属

编辑:
不好意思。。。我没想到有人会为我写它,我只是不认为我非常失败的尝试会帮助任何人看到我想要做什么,所以我只是解释了。

这是我目前的代码,我知道它有点工作。我正在编辑以前的 cookie,该 cookie 将网站引荐来源网址存储在 cookie 中。因此,就目前而言,cookie 将引荐来源存储在第一个页面浏览量上,然后如果您转到其他页面,它将显示{{utm_medium}}并在整个访问过程中继续显示。我希望它不显示引荐来源网址,而是输出一个 cookie,如果可能的话,它会显示{{utm_source}} | {{utm_medium}} | {{utm_campaign}}......

再次感谢您的任何帮助或指示或文章。我真的很感激。

<script> //get referrer info and shorten it
var ref = {{Referrer}}
function extractDomain(url) {
  var domain;
  //find & remove protocol (http, ftp, etc.) and get domain
  if (url.indexOf("://") > -1) {
    domain = url.split('/')[2];
  } else {
    domain = url.split('/')[0];
  }
  //find & remove port number
  domain = domain.split(':')[0];
  return domain;
}
ref = extractDomain(ref);
//create cookie 
function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
  } else var expires = "";
  document.cookie = name + "=" + value + expires + "; path=/";
}
var cookie = "";
//check if UTMs are present and set cookie content to the source utm  
if ({{utm_source}}) {
  createCookie("utmsource", cookie + {{utm_source}}, 1000)
} else if ({{utm_medium}}) {
  createCookie("utmsource", cookie + "Email", 1000)
    //check if referrer is present and set cookie content to the referrer
} else if ({{utm_campaign}}) {
  createCookie("utmsource", cookie + "{{utm_campaign}}", 1000)
} else if {
  createCookie("utmsource", cookie + "Email", 1000)
};
</script>

使用 cookie + something 时,不会更新cookie字符串。因此,每次执行此操作时,您只是与此字符串的原始空值连接。不要多次调用setcookie,而是在测试不同变量时更新 cookie 字符串,然后在末尾使用组合值调用 setcookie

您不应该在每个测试之间使用else if,因为如果第一个变量不存在,这只会将第二个变量添加到 cookie 中。但是您希望将所有变量放入cookie中。

var cookie = "";
if ({{utm_source}}) {
    cookie += {{utm_source}};
}
if ({{utm_medium}}) {
    cookie += ' | ' + {{utm_medium}};
} else {
    cookie += ' | Email';
}
if ({{utm_campaign}}) {
    cookie += ' | ' + {{utm_campaign}};
} else {
    cookie += ' | Email';
}
setcookie('utm_source', cookie, 1000);