I have a project called BRPS, which has an old client script brps.js. Whenever this client request data from BRPS server, the server will increase the requests count and it has a statistics page for showing the count. Recently, a new client is implemented, gas.js. This new client doesn’t communicate with BRPS server, I need to find a way to get a statistic number about how many requests it has been made. I don’t want to write more code on my server to log those requests. So, Google Analytics is the best option for me.
1 Non-asynchronous method
function _track() { try { var pageTracker = _gat._getTracker("UA-#######-#"); pageTracker._setDomainName("none"); pageTracker._setAllowLinker(true); pageTracker._trackPageview(); } catch(err) { } } if (window._gat) { _track(); } else { $.getScript(('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js', function(){ _track(); }); }
With the code above, my script can track requests from different domains1, which are not mine. I didn’t assign a path via pageTracker._trackPageview('/path/something'), because I want to see where exactly the request are made from. The UA-#######-# is only used by this script and I don’t need to log status such as /status/success or /status/failed.
2 Filters
I created a new profile and two more based on the first one. The last two are using filter each. The first filter is
Custom filter | Advanced | |
FieldA | Hostname | (.*) |
FieldB | Request URI | (.*) |
Output | Request URI | $A1$B1 |
The profile with this filter can see results like example.com/foobar. A sample output:
The second one is
Custom filter | Advanced | |
FieldA | Hostname | (.*) |
FieldB | unused | |
Output | Request URI | $A1 |
The profile with this filter can see results like example.com, I would like to know which websites are top users. A sample output:
3 Asynchronous method
I knew there was a method called asynchronous tracking. But I wasn’t catching it when I saw the code using JavaScript Array _gaq[] to store commands. At first, I thought that’s kind of bad. They embedded ga.js to read that array every time? Did script clean it up?
I was wrong until I read this:
When Analytics finishes loading, it replaces the array with the _gaq object and executes all the queued commands. Subsequent calls to _gaq.push resolve to this function, which executes commands as they are pushed.
So, my _track() needs a little modification:
function _track() { var _gaq = window._gaq || []; _gaq.push(['_setAccount', 'UA-#######-#']); _gaq.push(['_setDomainName', 'none']); _gaq.push(['_setAllowLinker', 'true']); _gaq.push(['_trackPageview']); if (!window._gaq) window._gaq = _gaq; }
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.