Skip to content

Instantly share code, notes, and snippets.

@iampatgrady
Last active April 18, 2022 23:23
Show Gist options
  • Save iampatgrady/622f3e3fc2a938dc59566b2d2e5a137f to your computer and use it in GitHub Desktop.
Save iampatgrady/622f3e3fc2a938dc59566b2d2e5a137f to your computer and use it in GitHub Desktop.
Proof-of-concept for setting and managing a 30-minute session ID as a GTM Custom Javascript Variable.
function(){
const storageName = "session_id_with_expiry";
function genId() {
return ([1e8]+-1e3).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
function setSessionId(name, value, ts) {
var item = {
"value": value,
"expiry": ts
}
localStorage.setItem(name, JSON.stringify(item));
}
function getSessionId(name) {
const ttl = 1000*60*30; // 30 mins
const date = new Date();
const dateTimeNow = date.getTime();
const ts = date.setTime(dateTimeNow + ttl);
var id = localStorage.getItem(name);
var item = JSON.parse(id);
if(!id){
setSessionId(name,genId(),ts)
} else {
if(dateTimeNow > item.expiry){
setSessionId(name,genId(), ts);
} else {
setSessionId(name,item.value, ts);
}
}
id = localStorage.getItem(name);
item = JSON.parse(id);
return item.value;
}
return getSessionId(storageName);
}
@iampatgrady
Copy link
Author

iampatgrady commented Apr 18, 2022

This variable will update the 30-minute expiry with every action on the site, extending the session timer. It will persist the same session ID as long as the expiry timer is active. Once the object expires, it will set a new session ID. Local Storage doesn't have a native method to manage "expiry" so we have to artificially manage it.

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