Search code examples
javascriptgoogle-analyticsuniversal-analytics

Disable async Google Analytics loading


I have this code decorating urls with Analytics' cookie in my webpage.

var tracker = window[window.GoogleAnalyticsObject].getAll()[0];
new window.gaplugins.Linker(tracker).decorate("http://www.toto.com");

This occurs an error :

window[window.GoogleAnalyticsObject].getAll is not a function

window.gaplugins is undefined

Like Google Analytics load its plugin asynchrously, i imagine getAll() and gaplugins.linker functions are not declared yet. I can't wait the DOM ready, so i would like to force synchrously GA plugin loading.

Thanks for your help


Solution

  • Using the documentation here (cf Eduardo comments), we could Post a message to the child iframe :

     <iframe id="destination-frame" src="https://destination.com"></iframe>
     <script>
          ga('create', 'UA-XXXXX-Y', 'auto');
          ga(function(tracker) {
               // Gets the client ID of the default tracker.
               var clientId = tracker.get('clientId');
    
               // Gets a reference to the window object of the destionation iframe.
               var frameWindow = document.getElementById('destination-frame').contentWindow;
               // Sends the client ID to the window inside the destination frame.
               frameWindow.postMessage(clientId, 'https://destination.com');
          });
     </script>
    

    And in the iframe side :

     window.addEventListener('message', function(event) {
          // Ignores messages from untrusted domains.
          if (event.origin != 'https://destination.com') return;
          ga('create', 'UA-XXXXX-Y', 'auto', {
               clientId: event.data
          });
     });