Javascript 有条件地加载Google分析

Javascript 有条件地加载Google分析,javascript,google-analytics,Javascript,Google Analytics,我需要从我们的分析报告中筛选内部QA人员 我们目前在网站中有代码,如果访问者是“学生”角色,则显示/隐藏信息div: $(document).ready(function(){ if($.inArray('student',ENV['current_user_roles']) === 1 && $.inArray('student',ENV['current_user_roles']) === 1 ){ if ($.inArray('teacher',ENV['current

我需要从我们的分析报告中筛选内部QA人员

我们目前在网站中有代码,如果访问者是“学生”角色,则显示/隐藏信息div:

$(document).ready(function(){
if($.inArray('student',ENV['current_user_roles']) === 1 && $.inArray('student',ENV['current_user_roles']) === 1 ){
  if ($.inArray('teacher',ENV['current_user_roles']) == -1 ){
  paramArray = window.location.href.split('/');
  if (paramArray.indexOf('assignments') == -1 && paramArray.indexOf('settings') == -1 && paramArray.indexOf('grades') == -1 && paramArray.indexOf('quizzes') == -1  && paramArray.indexOf('users') == -1){ 
    var l = $('#right-side-wrapper a.edit_link.button.button-sidebar-wide'); 
    if(l===null || l.length===0){
      $('body').removeClass('with-right-side');
    }
  }
}
} 
});
我不太精通JavaScript,但似乎应该有一种简单的方法来重复使用此代码,但将google analytics跟踪代码包装在其中,并且仅当用户的角色为“student:”时才加载它

$(document).ready(function(){
if($.inArray('student',ENV['current_user_roles']) === 1 && $.inArray('student',ENV['current_user_roles']) === 1 ){
  if ($.inArray('teacher',ENV['current_user_roles']) == -1 ){
    var _gaq=[["_setAccount","UA-xxxxxxxx-1"],["_trackPageview"]];
    (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
    g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js";
    s.parentNode.insertBefore(g,s)}(document,"script"));
}
} 
});
根据我在互联网上看到的情况,我尝试了上述方法,但这种方法并没有成功地过滤掉非学生


有什么建议吗?

也许你可以尝试使用Cookies。只需在QA工作站上设置cookie,如果设置了cookie,则不会调用Google代码。

代码的一个问题是,
\u gaq
将是一个局部变量,与ga.js加载的
\u gaq
对象不同。由于
\u setAccount
&
\u trackPageview
不在全局
\u gaq
中,因此不应跟踪任何内容

页面中是否有其他一组分析代码

建议:

  • 将加载Google Analytics的代码放在页面标题中,但省略
    \u setAccount
    &
    \u trackPageview
    部分
  • 在页面加载时,有条件地推送
    \u setAccount
    \u trackPageview
    命令
在页面标题中,类似于:

<script type="text/javascript">
var _gaq = _gaq || [];
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
$(document).ready(function(){
  if($.inArray('student',ENV['current_user_roles']) === 1){
    _gaq.push("_setAccount","UA-xxxxxxxx-1");
    _gaq.push("_trackPageview");
  } 
});