Wherelse Blog

Google Analytics排除localhost访问

2021-04-27 · 2 min read

Google Analytics excludes localhost access

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

Gridea原主题GA脚本引用方式:

//<%= 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引用的方式

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

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