Skip to content

Instantly share code, notes, and snippets.

@appikonda
Created March 27, 2023 07:20
Show Gist options
  • Save appikonda/3b2789e9962d0bd77d372adf38f980b7 to your computer and use it in GitHub Desktop.
Save appikonda/3b2789e9962d0bd77d372adf38f980b7 to your computer and use it in GitHub Desktop.
create and retrieve cookies
function utmCookieTag() {
const queryString = window.location.search; // url query string
const urlParams = new URLSearchParams(queryString); // get parameters in url
// get required parameters for the cookie management
const utm_medium_value = urlParams.get('utm_medium')
if (utm_medium_value) {
const previousCookie = getCookie("_utmMedium"); // check for previous cookie
if (previousCookie) {
// if prev cookie exists, get expiration date from _expireUtmMedium cookie
let prevExpDate = getCookie("_expireUtmMedium");
let exDate =new Date(prevExpDate); // Date conversion
const updated_utm_medium_value = previousCookie + ":" + utm_medium_value; // concat new utm_medium value to prev cookie
setCookie("_utmMedium", updated_utm_medium_value, exDate);
} else {
let exDate = getExpirationDate(14);
setCookie("_utmMedium", utm_medium_value, exDate) // create new _utmMedium cookie
setCookie("_expireUtmMedium", exDate, exDate); // create _expireUtmMedium to keep track of expiration date
}
}
}
// expiration date from number of days
function getExpirationDate(exdays){
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
return d;
}
// create cookie
function setCookie(cname, cvalue, date) {
let expires = "expires=" + date.toUTCString();
document.cookie =cname + "=" + cvalue + ";" + expires + ";path=/";
}
// retrieve cookie
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
console.log("ca: " + ca)
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
console.log(c);
return c.substring(name.length, c.length);
}
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment