In the case where you manually want to decorate a link with the linker parameter, i.e. the link is not a valid anchor link, or the final tracking page is accessed by user in a non direct way: File Download, Extension Installation, ect...
/**
* Returns the Google Analytics tracker linker parameter.
* @param {String} UA_CODE
* @returns {?String}
*/
function getLinkerParameter(UA_CODE) {
var linker = [];
var trackers = ga.getAll();
if(trackers.length > 0) {
for (i = 0, len = trackers.length; i < len; i += 1) {
if (trackers[i].get('trackingId') === UA_CODE) {
return trackers[i].get('linkerParam');
}
}
}
return null;
}
/**
* Sets the Google Analytics tracker linker parameter
* on callback from GA.
*/
ga(function() {
var trackers = ga.getAll();
var linker = trackers[0].get('linkerParam');
console.log('linker-param', linker);
document.cookie = 'ga-linker=' + '?' + linker + ';path=/';
});
Once a user arrives at a page on the destination domain with a linker parameter in the URL, analytics.js or gtag.js needs to know to look for that parameter.
ga('create', 'UA-XXXXXX-X', 'auto', {
allowLinker: true
});
gtag('config', 'GA_TRACKING_ID', {
'linker': {
'accept_incoming': true
}
});