Skip to content

Instantly share code, notes, and snippets.

@smhmic
Forked from sahava/allowlinker-ga.js
Last active October 22, 2020 00: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 smhmic/c82142190954341152c4991f52bceec7 to your computer and use it in GitHub Desktop.
Save smhmic/c82142190954341152c4991f52bceec7 to your computer and use it in GitHub Desktop.
This script reproduces Google Analytics' (analytics.js) allowLinker/autolinker logic, resulting in a function that returns the GA client id, but only if the autolinker parameter is valid. Uses the "old" linker plugin format. You can also pass a string as an argument to check if that string is a valid linker parameter.
// Mirrors analytics.js logic to validate autolinker param, and returns cid if valid.
// Returns false if autolinker param found, but invalid.
// Otherwise returns undefined.
var getCidFromAutolinker = function(str) {
var joiner = function (cidGid, offset) {
var a = new Date,
b = window.navigator,
c = b.plugins || [];
var d = [cidGid, b.userAgent, a.getTimezoneOffset(), a.getYear(), a.getDate(), a.getHours(), a.getMinutes() + offset];
for (var e = 0; e < c.length; ++e) {
d.push(c[e].description);
}
return jumble(d.join('.'));
};
var joiner2 = function (cidGid, offset) {
var a = new Date,
b = window.navigator,
c = a.getHours() + Math.floor((a.getMinutes() + offset) / 60);
return jumble([cidGid, b.userAgent, b.language || "", a.getTimezoneOffset(), a.getYear(), a.getDate() + Math.floor(c / 24), (24 + c) % 24, (60 + a.getMinutes() + offset) % 60].join("."));
};
var jumble = function (arr) {
var b = 1, c;
if (arr) {
for (b = 0, c = arr.length - 1; 0 <= c; c--) {
var d = arr.charCodeAt(c);
b = (b << 6 & 268435455) + d + (d << 14);
d = b & 266338304;
b = 0 != d ? b ^ d >> 21 : b
}
}
return b.toString();
};
var linker = /[?&#]_ga=([^&#]+)/.exec(str||location.href);
if( ! linker ) return;
linker = linker[1];
var a = linker.indexOf('.'), b, c, d, fingerprint, cidGid, cid;
if (a > -1) {
b = linker.substring(0, a);
c = linker.substring(a + 1);
d = c.indexOf(".");
fingerprint = c.substring(0, d);
cidGid = c.substring(d + 1);
cid = cidGid.split('-')[1];
}
if (cidGid) {
cidGid = cidGid.split('-').join('');
return ( fingerprint === joiner(cidGid, 0) ||
fingerprint === joiner(cidGid, -1) ||
fingerprint === joiner(cidGid, -2) ||
fingerprint === joiner2(cidGid, 0) ||
fingerprint === joiner2(cidGid, -1) ||
fingerprint === joiner2(cidGid, -2) ) ? cid : false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment