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

前端 未结 7 2275
鱼传尺愫
鱼传尺愫 2021-01-31 08:44

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

7条回答
  •  终归单人心
    2021-01-31 09:23

    At the time of writing, here in September 2013,
      Google Analytics has a new JavaScript API.

    After you've included Google's new "analytics.js" asynchronous snippet, use the send pageview command to track pages:

      ga('send','pageview');

    After your pushState madness, use this send pageview command to track your asynchronous navigation. According to Google's Documentation on Page Tracking with Analytics.js, the send pageview command will magically read and track the new location given by pushState, as it will, in the moment the send pageview command is called, use the following values by default (though you can specify them):

    var locationToTrack = window.location.protocol+'//'
      +window.location.hostname 
      +window.location.pathname 
      +window.location.search;
    
    var titleToTrack = document.title;
    
    var pathToTrack = location.pathname+location.search;
    

    Note, Google's standard analytics snippet includes an initial send pageview command.

    Update:

    I've implemented Google Analytics tracking on my website in the way above that I described -- however, it does not seem to be successfully tracking any of the pushState page views.

    I'm going to try specifying the location, title, and page name explicitly on the send pageview command, and see if GA tracks properly.

    I'll post back with the results, unless I forget.

提交回复
热议问题