Tricks to deal with customized Google Analytics and Google Tag Manager integrations

In the past years, I worked on implementing Google Analytlics and Google Tag Manager in a lot of differences scenearios and almost any kind of integrations. So I’m gonna show you some code snippets that may help you integrating Google Tag Manager and Google Analytics into your libraries in the best way possible.

Checking is Universal Analytics is available

Most integrations I’ve seen does check for the ga object within the DOM before trying to push something to it. This is really nice, and a check that should be done ALWAYS, but Universal Analytics allows you to change the default name for the “ga” object, so under those situations our code may not work as we’re expecting.

Luckly for us, Universal Analytics creates another variable, named window.GoogleAnalyticsObject, that will allow us to grab the current object name being used by Universal Analytics.

So using the following code will allow us to check is Google Analytics is really available even if the current name has been changed:

if(window.GoogleAnalyticsObject && typeof(window[GoogleAnalyticsObject])=="function"){ 
   // Code Here

Checking for current dataLayer object name for Google Tag Manager

Google Tag Manager users the “dataLayer” name by default, but it may changed to use any other name.

This piece of code will allow us to find the right dataLayer name dinamically:

var gtm_datalayer_names=[];
    for(i in google_tag_manager){

The we could do something like:


We’ll even be able to send pushes to all the different dataLayer available on the current page:

        var i = window.gtm_datalayer_names.length;
           var dlName = gtm_datalayer_names[i];
           window[gtm_datalayer_names] = window[gtm_datalayer_names] || [];                 
              'event': 'my-event-name',
              'dataLayerName': gtm_datalayer_names[i]

Author: David Vallejo

Google Analytics Consultant and implementer. I have some experience with Google Tag Manager Follow me: @thyng

1 thought on “Tricks to deal with customized Google Analytics and Google Tag Manager integrations”

Leave a Reply

Your email address will not be published. Required fields are marked *