Obtaining Google Analytics ClientID with Tag Manager
Anyone dealing with Measurement Protocols / CRMs may always need to store and retrieve ClientID for tasks like sending offline transactions, managing leads/ refunds etc.
This post assumes you are using GTM for GA implementation with Universal Analytics.
Create a Custom JavaScript variable as below.function(){ return ga.getAll()[0].get('clientId'); }
Or define this as a JS variable.
Above script can be used when there is only one GA ID firing in the site, if multiple GA’s are present, use the script below specifying the GA ID:
function() { var trackers = ga.getAll(); var i, len; for (i = 0, len = trackers.length; i < len; i += 1) { if (trackers[i].get('trackingId') === "UA-XXXXXXX-1") { return trackers[i].get('clientId'); } } return 'nil'; }– Now we are almost done, what remains is to send this data to Google Analytics. As usual, many of us will send this a custom dimension or metrics or both.
We are done now. To make sure everthing is working, look for the variable created in GTM preview pane.