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

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)


February 2018 Update - Global Site Tag (gtag.js)

Google Analytics has a new tracking code snippet, so the other answers might not work for gtag.

This is the default tracking code. It only runs once even though we try to run it each URL changes.

gtag('config', 'GA_TRACKING_ID');

But with a page_path parameter we can make GA run manually.

gtag('config', 'GA_TRACKING_ID', {'page_path': '/new-page.html'});

And we can make something like this.

var origin = window.location.protocol + '//' + window.location.host;
var pathname = window.location.href.substr(origin.length);
gtag('config', 'GA_TRACKING_ID', {'page_path': pathname});

Single page application tracking with gtag.js (Google documentation)


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']);

Recent answer (2017)

You can now use Google's autotrack.js, a script that enhances analytics.js.

It includes a plugin that automatically tracks URL changes for single page applications.

You just need to include the script and the following line in your html:

ga('require', 'urlChangeTracker');