Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Analytics: How to track pages in a single page application?

Currently in my website, I used HTML5's pushState() and popState in links to increase the speed. However, this doesn't really change the real URL and it looks like it will affect and mess up the Google Analytics's code. (doesn't show a url change) Is there a possible solution for this? Thanks,

like image 262
Derek 朕會功夫 Avatar asked Mar 09 '12 03:03

Derek 朕會功夫


People also ask

How does Google Analytics work with a single page application?

In the case of traditional websites, Google Analytics works fine because the code snippet is loaded every time the page is loaded. But in the case of a single page application, content is loaded dynamically which means the page refresh happens only once and Google Analytics runs only once on the page.

How do I track a single page application?

Go to Tags → New, name it “GA – Pageview – pageview”, choose Google Analytics as the Tag Type and Page View as the Track Type, select your GA tracking ID and as a trigger select the new custom pageview trigger we just created.

How do I track a specific page in Google Analytics?

The first thing you need to do is open up Google Analytics, and then go to the behavior tab. In the behavior tab, click on the site content, then content drilldown tab. Then, you simply need to click the search icon in the bar, and you will be greeted with analytics specific to that individual page/post.

Do I need the Google Analytics tracking code on every page?

You do need to put Google Analytics on every page that you are interested in tracking. Depending on what website builder you are using, it is done automatically for you.


2 Answers

If you are using the newer analytics.js API, Google's documentation requires the following code to trigger the event:

ga('send', 'pageview', '/some-page'); 

If you are using the older ga.js API, David Walsh suggests AJAX websites to use the _gaq.push method:

_gaq.push(['_trackPageview', '/some-page']); 
like image 175
Derek 朕會功夫 Avatar answered Oct 01 '22 05:10

Derek 朕會功夫


I know it's old question but since this question is first result in Google about tracking pushState() in Google Analytics and all answers are wrong I decided to answer it.

In other answers they mentioned to use directly ga('send' ..... ) but this is wrong way to do it.

First you have to 'set' parameters and then use 'send' to track it.

If you want to update only url, use following code

// set new url   ga('set', 'page', '/new-page');    // send it for tracking  ga('send', 'pageview');

If you want to update url and title, add title parameter to it

// set new url and title  ga('set', {    page: '/new-page',    title: 'New Page'  });    // send it for tracking  ga('send', 'pageview');

Source Single Page Application Tracking - Web Tracking (analytics.js)

like image 31
Nicolo Avatar answered Oct 01 '22 04:10

Nicolo