记忆一隅

Google Analytics排除localhost访问

2021-04-27 · 2 min read
网络

Google Analytics excludes localhost access

使用Google Analytics统计网站访问量时,即使是访问本地预览localhost链接时,仍然会统计入网站访问量,这使访问量统计准确度有所下降。

Gridea原主题GA脚本在ejs文件中的引用方式:

//<%= site.customConfig.ga %>为跟踪ID
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= site.customConfig.ga %>"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', '<%= site.customConfig.ga %>');
</script> 

经过修改,通过js添加判断,排除localhost的GA加载

<% if (site.customConfig.ga) { %>
  <script>
  var host = window.location.hostname;
  const pattern = /localhost.*/;
  let pattern_re = new RegExp(pattern)
  if(!pattern_re.test(host))
  {
    let head = document.getElementsByTagName('head')[0];
    let script = document.createElement('script');
    script.src= "https://www.googletagmanager.com/gtag/js?id=<%= site.customConfig.ga %>";
    script.onload = function(){
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', '<%= site.customConfig.ga %>');
    };
    head.appendChild(script);
  }
  </script>

修改完后,测试之后,已不再统计localhost访问。