Search code examples
google-analyticstrackingstat

Tracking by id in url with Google Analytics


I want to track views for stories on my site. I want to use Google analytics to do this. Off the bat Im thinking of doing this:

pageTracker._trackEvent('Story', 'View', 'Title of story');

But I also would prefer to track with the story id as well that is passed in the url. So if I want to run a report in GA I would like to have the option of getting stats by story title or by story id that is passed via url. Is that possible?


Solution

  • GA by default does not strip parameters from the URL when _trackPageview is triggered, so you will see unique pages show up in your reports. For example, these two will show up as separate entries:

    /somePage.html?id=1
    /somePage.html?id=2
    

    edit:

    Okay, you can use this to get whatever url parameter you want:

    function getParam (n) {
      var x=new RegExp("[\\?&]"+n.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]")+"=([^&#]*)");
      var r=x.exec(window.location.href);  
      return(r==null)?'':r[1] ;
    }
    // example 
    var story = getParam('story'));
    

    now story has whatever value the story=xxx URL parameter value is, and you can use story as your category value in your event tracking argument