Track page views with Google Analytics

Original link: https://www.williamlong.info/archives/6928.html

GoogleAnalytics.jpg

Adding Google Analytics code to the webpage can automatically count the page views of the webpage. However, sometimes we need to count the page views of some virtual webpages, such as webpages loaded through Javascript, here we need to add some Google Analytics code, let me introduce the specific addition method.

First add the Google Analytics code on the web page. For the old version of Universal Analytics (analytics.js) the statistical code is:

<!– 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://ift.tt/WLyuNoI);

ga(‘create’, ‘TAG_ID’, ‘auto’);

ga(‘send’, ‘pageview’);

</script>

<!– End Google Analytics –>

The statistical code for the new version of Google Analytics 4 (gtag.js) is:

<!– Google tag (gtag.js) –>

<script async src=”https://ift.tt/uUGxIj3>

<script>

window.dataLayer = window.dataLayer || [];

function gtag(){dataLayer.push(arguments);}

gtag(‘js’, new Date());

gtag(‘config’, ‘TAG_ID’);

</script>

<!– Google tag (gtag.js) –>

Later, when a specific virtual page is loaded, adding a piece of Javascript code will increase the number of virtual page views.

For older versions of Universal Analytics (analytics.js), the way to count specific page views is:

ga(‘create’, ‘TAG_ID’, ‘auto’);

ga(‘send’, ‘pageview’, pathname);

Where pathname is the path name of the specified virtual URL, which needs to start with “/”.

Example:

ga(‘create’, ‘UA-1’, ‘auto’);

ga(‘send’, ‘pageview’, location.pathname);

For the new version of Google Analytics 4 (gtag.js), the way to count specific page views is:

gtag(‘event’, ‘page_view’, {

page_title: ‘<Page Title>’,

page_location: ‘<Page Location>’,

page_path: ‘<Page Path>’,

send_to: ‘<TAG_ID>’

})

Where Page Path is the path name of the specified virtual URL, which needs to start with “/”.

Example:

gtag(‘event’, ‘page_view’, {

page_title: document.title,

page_location: window.location.href,

page_path: window.location.pathname,

send_to: ‘G-1’

});

These are the methods for tracking virtual web pages in both the old and new versions of Google Analytics.

This article is reprinted from: https://www.williamlong.info/archives/6928.html
This site is for inclusion only, and the copyright belongs to the original author.