I checked how Analytics 4 handles cross domain tracking and come up with the following code based on the original implementation. This code will append the new _gl
param to the given url.
You will need to provide your measurement ID without the starting G-
to the getLinkerParam
function.
function getUrl(url) {
var linkerParam;
try {
linkerParam = getLinkerParam('*** MEASUREMENT ID without G- ***');
} catch (e) {
}
return (linkerParam ? url + '?' + linkerParam : url);
}
function getLinkerParam(measurement_id) {
var data = {};
var parts1 = document.cookie.match('(^|;)\\s*_ga\\s*=\\s*([^;]+)').pop().split('.');
parts1.shift();
parts1.shift();
data._ga = parts1.join('.');
var parts2 = document.cookie.match('(^|;)\\s*_ga_' + measurement_id + '\\s*=\\s*([^;]+)').pop().split('.');
parts2.shift();
parts2.shift();
data['_ga_' + measurement_id] = parts2.join('.');
function kf() {
for (var a = lf, b = {}, c = 0; c < a.length; ++c)
b[a[c]] = c;
return b
}
function mf() {
var a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
a += a.toLowerCase() + "0123456789-_";
return a + "."
}
var lf,
nf, qf;
function of(a) {
lf = lf || mf();
nf = nf || kf();
for (var b = [], c = 0; c < a.length; c += 3) {
var d = c + 1 < a.length,
e = c + 2 < a.length,
f = a.charCodeAt(c),
h = d ? a.charCodeAt(c + 1) : 0,
k = e ? a.charCodeAt(c + 2) : 0,
l = f >> 2,
n = (f & 3) << 4 | h >> 4,
q = (h & 15) << 2 | k >> 6,
r = k & 63;
e || (r = 64, d || (q = 64));
b.push(lf[l], lf[n], lf[q], lf[r])
}
return b.join("")
}
var Df = function (a) {
var b = [],
c;
for (c in a)
if (a.hasOwnProperty(c)) {
var d = a[c];
void 0 !== d && d === d && null !== d && "[object Object]" !== d.toString() && (b.push(c), b.push(of(String(d))))
}
var e = b.join("*");
return ["1", Cf(e), e].join("*")
},
Cf = function (a, b) {
var c = [window.navigator.userAgent, (new Date).getTimezoneOffset(), window.navigator.userLanguage || window.navigator.language, Math.floor((new Date).getTime() / 60 / 1E3) - (void 0 === b ? 0 : b), a].join("*"),
d;
if (!(d = qf)) {
for (var e = Array(256), f = 0; 256 > f; f++) {
for (var h = f, k = 0; 8 > k; k++)
h = h & 1 ? h >>> 1 ^ 3988292384 : h >>> 1;
e[f] = h
}
d = e
}
qf = d;
for (var l = 4294967295, n = 0; n < c.length; n++)
l = l >>> 8 ^ qf[(l ^ c.charCodeAt(n)) & 255];
return ((l ^ -1) >>> 0).toString(36)
};
return "_gl=" + Df(data);
}