I am incredibly new and novice in this and trying to write a simple code that will:
- Set cookies depending on URL parameters.
- Keep these cookies across the website even when the parameters are no longer in the URL
I was able to do bullet one with some basic tutorials but Im failing at bullet 2. WHen the visitor clicks any link in the menu etc. the parameters are removed as the page refreshes and my cookie values also empty.
Im using this API: https://github.com/js-cookie/js-cookie/tree/latest#readme
This is the code I have right now: (I expect the code to overwrite the cookie ONLY if there is a non-empty new parameter. If there are no parameters set or if it is empty I do want to keep the original value. I want to keep the cookie for a day or until the session ends)
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js"></script>
<script>
// Parse the URL
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 source = getParameterByName('utm_source');
var medium = getParameterByName('utm_medium');
var campaign = getParameterByName('utm_campaign');
// Set the cookies
if(source !== null || source !== ""){Cookies.set('utm_source', source, { expires: 1 }, { domain: 'domain.com' });
}
if(medium !== null || source !== "")
{Cookies.set('utm_medium', medium, { expires: 1 }, { domain: 'domain.com' });
}
if(campaign !== null || source !== "")
{Cookies.set('utm_campaign', campaign, { expires: 1 }, { domain: 'domain.com' });
}
</script>
Thanks a bunch!