4

使用Google Analytics跟踪网页浏览

 1 year ago
source link: https://www.williamlong.info/archives/6928.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

使用Google Analytics跟踪网页浏览

2022-9-18 14:52:12 | 作者: 月光 | 分类: 编程开发 | 评论: 0 | 浏览: 121

  在网页上添加Google Analytics(分析)的代码,可以自动统计到网页的浏览量,不过,有时候我们需要统计一些虚拟网页的浏览量,例如通过Javascript加载出来的网页,这里就需要再添加一些Google Analytics代码了,下面我就介绍一下具体添加方法。

  先在网页端添加Google Analytics(分析)的代码。对于老版本Universal Analytics(analytics.js)统计代码是:

<!-- Google Analytics -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'TAG_ID', 'auto');
  ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

  对于新版本Google Analytics 4 (gtag.js)的统计代码是:

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TAG_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'TAG_ID');
</script>
<!-- Google tag (gtag.js) -->

  之后,当特定的虚拟页面加载之后,增加一段Javascript代码将虚拟页面浏览量增加。

  对于老版本Universal Analytics(analytics.js),统计特定页面浏览量的方法是:

ga('create', 'TAG_ID', 'auto');
ga('send', 'pageview', pathname);  

  其中pathname是指定虚拟URL的路径名,需要以“/”开头。

ga('create', 'UA-1', 'auto');
ga('send', 'pageview', location.pathname); 

  对于新版本Google Analytics 4 (gtag.js),统计特定页面浏览量的方法是:

gtag('event', 'page_view', {
  page_title: '<Page Title>',
  page_location: '<Page Location>',
  page_path: '<Page Path>',
  send_to: '<TAG_ID>'
})

  其中Page Path是指定虚拟URL的路径名,需要以“/”开头。

gtag('event', 'page_view', {
    page_title: document.title,
    page_location: window.location.href,
    page_path: window.location.pathname,
    send_to: 'G-1'
});

  以上就是Google Analytics(分析)新老两个版本来跟踪虚拟网页的方法。

使用Google Analytics跟踪网页浏览

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK