Check if Google Analytics or Universal Analytics is installed?

岁酱吖の 提交于 2019-12-10 15:50:04

问题


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.


回答1:


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.




回答2:


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



回答3:


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>


来源:https://stackoverflow.com/questions/25510183/check-if-google-analytics-or-universal-analytics-is-installed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!