JavaScripter
JavaScripter

Reputation: 4842

make google analytics tracking Hash URLs for single page application

Here is my initial question: Enable google analytics for single page site with # views

I took this answer: https://stackoverflow.com/a/18626897/765498

However, I found that, this answer just send click events. What I'd like to achieve is that, make google analytics records different hash urls.

I read this article: tracking hash urls, but have no idea how to make this happen. I tried this codes, seems doesn't work. What I'd like to achieve is to make the different page shows as 'active Page'. for example, /register.html#/p1 and /register.html#/p2 and /register.html#/p3 and /register.html#/p4

  <script stype="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXX-1']);
  _gaq.push(['_trackPageview', "/" + window.location.hash]);
  (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','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXX-1', 'xxxxxxxx.com');
  ga('set','page','/register.html')
  ga('send', 'pageview');


</script>   

Upvotes: 1

Views: 2635

Answers (1)

Tom
Tom

Reputation: 582

You have to listen for hash changes.

$(window).on('hashchange', function() {
    _gaq.push(['_trackPageview', "/" + window.location.hash]);
});

Upvotes: 3

Related Questions