Skip to content

Instantly share code, notes, and snippets.

@csinghdev
Forked from daolf/attribution.js
Created November 21, 2020 18:38
Show Gist options
  • Save csinghdev/498540e4477361994f75c79d9cace6da to your computer and use it in GitHub Desktop.
Save csinghdev/498540e4477361994f75c79d9cace6da to your computer and use it in GitHub Desktop.
https://jennamolby.com/how-to-use-cookies-to-capture-url-parameters/
// Parse the URL
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var utm_source = getParameterByName('utm_source');
var utm_medium = getParameterByName('utm_medium');
var utm_campaign = getParameterByName('utm_campaign');
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function setCookie(cname, cvalue) {
const d = new Date();
// On Safari, max duration for cookies is 7 days.
d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30 = number of days
const expires = `expires=${d.toUTCString()}`;
// Using the new SameSite attribute: https://web.dev/samesite-cookie-recipes/
document.cookie = `${cname}=${cvalue};${expires};path=/;SameSite=Strict`;
// Fallback for legacy browsers: https://web.dev/samesite-cookie-recipes/
document.cookie = `${cname}=${cvalue};${expires};path=/;Secure`;
}
// Set the cookies
if(utm_source != "" && getCookie("utm_source") == "") {
setCookie('utm_source', utm_source);
}
if(utm_medium != "" && getCookie("utm_medium") == "") {
setCookie('utm_medium', utm_medium);
}
if(utm_campaign != "" && getCookie("utm_campaign") == "") {
setCookie('utm_campaign', utm_campaign);
}
if(document.referrer != "" && getCookie("referrer") == "") {
setCookie('referrer', document.referrer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment