Skip to content

Instantly share code, notes, and snippets.

@ahmadawais
Forked from daolf/attribution.js
Created July 24, 2021 13:05
Show Gist options
  • Save ahmadawais/fdd15740d8bfbf3628e729adf8585e9a to your computer and use it in GitHub Desktop.
Save ahmadawais/fdd15740d8bfbf3628e729adf8585e9a to your computer and use it in GitHub Desktop.
https://jennamolby.com/how-to-use-cookies-to-capture-url-parameters/
let YOUR_DOMAIN = "YOUR_DOMAIN.TLD" // ex: scrapingbee.com
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
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');
var utm_term = getParameterByName('utm_term');
var now = new Date();
now.setMonth( now.getMonth() + 1 );
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 "";
}
// Set the cookies
if(utm_source != "" && getCookie("utm_source") == "") {
document.cookie = `utm_source=${utm_source}; domain=${YOUR_DOMAIN}; expires="${now.toUTCString()}"`
}
if(utm_medium != "" && getCookie("utm_medium") == "") {
document.cookie = `utm_medium=${utm_medium}; domain=${YOUR_DOMAIN}; expires="${now.toUTCString()}"`
}
if(utm_campaign != "" && getCookie("utm_campaign") == "") {
document.cookie = `utm_campaign=${utm_campaign}; domain=${YOUR_DOMAIN}; expires="${now.toUTCString()}"`
}
if(utm_term != "" && getCookie("utm_term") == "") {
document.cookie = `utm_term=${utm_term}; domain=${YOUR_DOMAIN}; expires="${now.toUTCString()}"`
}
if(document.referrer != "" && getCookie("referrer") == "") {
document.cookie = `referrer=${document.referrer}; domain=${YOUR_DOMAIN}; expires="${now.toUTCString()}"`
}
// Set the cookies
var utm_journey = getCookie("utm_journey");
var current_relative_path = location.href.replace(location.origin,'');
if (utm_journey != "") {
old_journey = atob(utm_journey)
new_journey = `${old_journey} - ${current_relative_path}`
document.cookie = `utm_journey=${btoa(new_journey)}; domain=${YOUR_DOMAIN}; path=/;`
} else {
document.cookie = `utm_journey=${btoa(current_relative_path)}; domain=${YOUR_DOMAIN}; expires="${now.toUTCString()}; path=/;`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment