Check if Google Analytics or Universal Analytics i

2019-06-27 19:47发布

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.

3条回答
乱世女痞
2楼-- · 2019-06-27 20:12

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

<a href="http://www.example.com" onclick="trackLink('http://www.example.com', event);">Visit example.com</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>
查看更多
聊天终结者
3楼-- · 2019-06-27 20:24
if (typeof window.ga === 'undefined') {
   // analytics does not exist
}
查看更多
贪生不怕死
4楼-- · 2019-06-27 20:29

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.

查看更多
登录 后发表回答