Skip to content

Instantly share code, notes, and snippets.

@holmberd
Last active October 13, 2022 21:41
Show Gist options
  • Save holmberd/b0b9c30d11d8c9cd8abd799ffd9e38dc to your computer and use it in GitHub Desktop.
Save holmberd/b0b9c30d11d8c9cd8abd799ffd9e38dc to your computer and use it in GitHub Desktop.
Google Analytics - Cross Domain Manual Link Tracking

Manually decorate a URL with the linker parameter for Google Tag Manager or Google Analytics

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...

Google Analytics

/**
 * 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;
}

Google Tag Manager Custom HTML Tag (Adding linker to cookie)

/**
 * 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=/';
    });

Configuring a site to accept linker parameters

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.

Analytics.js

ga('create', 'UA-XXXXXX-X', 'auto', {
  allowLinker: true
});

gtag.js

gtag('config', 'GA_TRACKING_ID', {
  'linker': {
    'accept_incoming': true
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment