admin管理员组

文章数量:1279112

I am trying, through javascript, to identify if Google Analytics or Universal Analytics is loaded.

Some clients still use the old Google Analytics and we want to roll out a javascript that collects data. So i then need to write code for both versions to make sure it gets tracked regardless if its the normal or universal version of analytics.

I am trying, through javascript, to identify if Google Analytics or Universal Analytics is loaded.

Some clients still use the old Google Analytics and we want to roll out a javascript that collects data. So i then need to write code for both versions to make sure it gets tracked regardless if its the normal or universal version of analytics.

Share Improve this question asked Aug 26, 2014 at 15:57 PatrickPatrick 5,59210 gold badges55 silver badges107 bronze badges 2
  • When you say old, you're talking about the version directly before the analytics.js stuff, right? How far back do you need to go? You don't need to go back to the Urchin days, do you? – Brad Commented Aug 26, 2014 at 16:02
  • Nope, just Google analytics and Universal analytics. – Patrick Commented Aug 27, 2014 at 8:48
Add a ment  | 

3 Answers 3

Reset to default 9

Classic GA uses the "_gaq" object, and UA uses the "ga" object, so you could check for the existence of either of those

if (_gaq) {
   // using classic GA; do whatever
}

or

if (ga) {
   // using UA; do whatever
}

Hope this helps.

if (typeof window.ga === 'undefined') {
   // analytics does not exist
}

From https://developer.mozilla/en-US/Firefox/Privacy/Tracking_Protection:

<a href="http://www.example." onclick="trackLink('http://www.example.', event);">Visit example.</a>
<script>
function trackLink(url,event) {
    event.preventDefault();
    //This is how you check that google analytics was loaded
    if (window.ga && ga.loaded) {
         ga('send', 'event', 'outbound', 'click', url, {
         'transport': 'beacon',
         'hitCallback': function() { document.location = url; }
       });
    } else {
        document.location = url;
    }
}
</script>

本文标签: javascriptCheck if Google Analytics or Universal Analytics is installedStack Overflow