handle urls with hash # with google analytics

2020-07-22 16:21发布

问题:

I'm developing a js single-page web application using a javascript client side mvc (angular.js in this case)

I added google analytic to the site, but from what I could see so far (at least in realtime) google doesn't take into account the part of the uri after the hash

that is I have a url like mydomain.com.ar/#/ideas/1 but for google analytics it looks just like mydomain.com.ar/

any idea?

回答1:

You need to parse the parameters after # and send the data by using _trackPageview in order to see them on your pages report.

and here is how to do it,

 var params = {},
     queryString = location.hash.substring(1), 
     regex = /([^&=]+)=([^&]*)/g, 
     m; 
 while (m = regex.exec(queryString)) { 
     params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
 }
 _gaq.push(['_trackPageview', queryString]);


回答2:

Use $window dependency and call on route change.

Also use GA 'set' to ensure routes are picked up for Google realtime analytics.

$scope.$on('$routeChangeSuccess', function() {
    $window.ga('set', 'page', $location.url());
    $window.ga('send', 'pageview');
});