Skip to content

Instantly share code, notes, and snippets.

@nurullah
Last active November 4, 2022 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nurullah/8a2a882e02ece0206d8344d28e066617 to your computer and use it in GitHub Desktop.
Save nurullah/8a2a882e02ece0206d8344d28e066617 to your computer and use it in GitHub Desktop.
Save the UTM parameteres in localStorage for a month
function saveUTMParameters() {
var params = Object.fromEntries(new URLSearchParams(document.location.search));
// utm_campaign exists
if (Object(params).hasOwnProperty('utm_campaign')) {
var date = new Date();
var expires_date = new Date(date);
expires_date.setMonth(date.getMonth() - 1);
// get current utm history or create empty array
var utm_history = JSON.parse(localStorage.getItem('utm_history')) || [];
if (utm_history.length > 0) {
var last_object = Object.assign({}, utm_history.slice(-1)[0]);
delete last_object.created_at;
// don't update if last object equal the new object
if (JSON.stringify(last_object) === JSON.stringify(params)) {
return false;
}
}
// add new object to the array after the created_at
Object.assign(params, { created_at: date.toISOString() });
utm_history.push(params);
// prepared unexpired data
var unexpired_utm_history = utm_history.filter(function(obj) => {
return obj.created_at >= expires_date.toISOString();
});
localStorage.setItem('utm_history', JSON.stringify(unexpired_utm_history));
}
}
window.addEventListener('load', saveUTMParameters);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment