Skip to content

Instantly share code, notes, and snippets.

@Dan0sz
Last active January 22, 2022 10:51
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 Dan0sz/96a5484b685f81ee61327f41eb660b41 to your computer and use it in GitHub Desktop.
Save Dan0sz/96a5484b685f81ee61327f41eb660b41 to your computer and use it in GitHub Desktop.
A JS snippet which generates a random UUID for usage in Google Analytics' tracking code.
const cyrb53 = function(str, seed = 0) {
let h1 = 0xdeadbeef ^ seed,
h2 = 0x41c6ce57 ^ seed;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};
let creationTime = new Date().getTime();
let expiryTime = creationTime + (30 * 24 * 3600 * 1000); // Change 30 to any number of days you want the UUID to be valid.
let clientIDSource = window.location.host + ";" + navigator.userAgent + ";" + navigator.language + ";" + creationTime;
// Only store client ID and its expiry time if it doesn't already exist and isn't expired yet.
if (window.localStorage) {
clientIDhashed = localStorage.getItem('GA_CLIENT_ID_HASHED');
clientIDexpiry = localStorage.getItem('GA_CLIENT_ID_EXPIRY');
// Start a fresh session or update when expired. Otherwise, do nothing.
if ((clientIDhashed === null && clientIDexpiry === null)
|| (clientIDhashed !== null && clientIDexpiry !== null && clientIDexpiry >= expiryTime)) {
localStorage.setItem('GA_CLIENT_ID_HASHED', cyrb53(clientIDSource).toString(16));
localStorage.setItem('GA_CLIENT_ID_EXPIRY', expiryTime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment