1 posts categorized "google analytics"

02/14/2009

BigIP: iRule to Insert Google Analytics Code

I knew that I could set up an irule in my BigIP LTM that would modify the HTML in a response back to the client and wanted to figure out how to do it. I also wanted to code something that could potentially be useful. Below is an irule that will insert Google Analytics tracking codes into your HTML responses. It works pretty well and don't worry, the rule below does not utilize any Web Property ID (the UA-######-#) by default, so you won't be funneling your page view and visit counts up into my blog's profile.
# irule_insertGA - by CCM - blog.techstacks.com
# The only thing you need to do is sert the value
# for 'gacode' so that it matches your Web Property ID
#
# The irule will insert the google analytics tracking code
# just before the closing body tag.
#
# To DO: It would be nice to store codes in a datagroup
# and have the irule insert the correct web property ID
# based on knowing which VIP it is applied to.

when RULE_INIT {
set ::find "</body>"
set gacode "INSERT_YOUR_UA_CODE_HERE"
set ::replace "<script type=\"text/javascript\"> var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\"); document.write(unescape(\"%%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\")); </script> <script type=\"text/javascript\"> try {var pageTracker = _gat._getTracker(\"$gacode\");pageTracker._trackPageview();} catch(err) {} </script> </body>"
}

when HTTP_RESPONSE {
STREAM::disable
if {[HTTP::header value Content-Type] contains "text"}{
STREAM::expression "@$::find@$::replace@"
STREAM::enable
}
}
This irule (12 lines (!) but one is really, really long) uses the STREAM::expression (Login Required) command to find your closing body tag and insert the tracking code in front of it. To use it, all you need to do is replace the value for gacode with your actual Web Property ID, assign a Stream profile to your VIP, and attach the rule. Open your site's home page and view source and the script should be at the bottom of page.


Advanced Web Metrics with Google Analytics