GTM Solutions Corner #4: Capturing existing classic GA calls

This is part 4 of a semi-regular series, dedicated to reusable GTM solutions for scenarios or issues we’ve encountered more than once. Last time, we looked at how to turn on-page classic Google Analytics calls to data layer pushes, and this time we’ll be looking at a supplement to that—what if the classic GA call you’re looking to capture is before GTM loads? This pretty much only matters for ecommerce, so that’s what the solution focuses on.

We start by defining some variables:

var gaq = window._gaq;
var ctdl_obj = {};
var ctdl_arr = [];

The second two are where we’re going to push some values a bit later, and the first one is getting the existing _gaq object.

for(i=0;i < gaq.length;i++){

Now we’re going to start looping through gaq to see what’s in there.

 if(gaq[i][0] === "_addTrans"){
    window.ctdl_obj.id = gaq[i][1];
    window.ctdl_obj.affiliation = gaq[i][2];
    window.ctdl_obj.revenue = gaq[i][3];

If we find a “_addTrans” which is the push that adds the transaction-level information, we write it into the ctdl_obj we created at the beginning, in Enhanced Ecommerce format.

 } else if(gaq[i][0] === "_addItem"){
    window.ctdl_arr.push({
          'id':gaq[i][2],
          'name':gaq[i][3],
          'category':gaq[i][4],
		      'price':gaq[i][5],
          'quantity':gaq[i][6]
        })

Then if it’s “_addItem”, the pushes which add items (obviously!) we push that into the ctdl_arr array we created earlier.

 } else if(gaq[i][0] === "_trackTrans"){
    dataLayer.push({
          'event': 'hcga_trans',
            'ecommerce': {
        		'purchase':{
          			'actionField' : window.ctdl_obj,
          			'products' : window.ctdl_arr
        					}
      					}
        			}
				);
  }
}

Finally, once we hit the “_trackTrans” push, we arrange all the stuff we’ve gathered into EE format and push it into the data layer.

Once you’ve added this in a custom HTML tag to fire where it’s needed, you’ll need to configure a GA tag to fire on the data layer push. The solution is also available in full on the Measurelab Github. Please drop me a line if you’ve got any questions or ideas for improvement!

Share:
Written by

Subscribe to our newsletter: