Skip to content

Instantly share code, notes, and snippets.

@daolf
Last active April 2, 2024 18:07
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save daolf/e66ec71c603cec4e502190788e75a2f6 to your computer and use it in GitHub Desktop.
Save daolf/e66ec71c603cec4e502190788e75a2f6 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=/;`
}
@joostvanhoof
Copy link

joostvanhoof commented Sep 7, 2020

For some reason, the Expires value was always set to Session instead of one month from now. I tried different things but it didn't work, so ended up using something that I already use, see below.

  • Function to set cookie
  • Added SameSite attribute with fallback for older browsers (see code comments for links with info)

Feel free to update the Gist with this!

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

@daolf
Copy link
Author

daolf commented Sep 7, 2020

This is nice! Thank you very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment