Programmatically add Google Analytics tracking code to ASP.NET sites

by Brad 11. January 2008 09:09

Typically our clients opt to use Google's free web stats package Google Analytics to track their site usage - and who can blame them! Anyway adding them to every project is a bit of a chore, so I decided to save time by adding it to my BasePage class. For those of you that don't create base pages - you should! It's great for situations like this where you want to apply or access some code in every page (I admit it's far more useful to make all UserControls inherit from a BaseUserControl than doing it at a page level - but its still good programming practice... All you have to do is create a class "BasePage" which inherits from System.Web.UI.Page then make all your aspx pages inherit from BasePage not System.Web.UI.Page.

Anyway here's how i added in the Google Analytics tracking code...

First add the following constant to your BasePage:

public const string GOOGLE_ANALYTICS_JAVASCRIPT = 
@" 
<script type=""text/javascript""> 
/* Google TRACKING CODE */ 
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""> 
var pageTracker = _gat._getTracker(""{0}""); 
pageTracker._initData(); 
pageTracker._trackPageview(); 
/* Google TRACKING CODE */ 
</script> 
"; 

Second add the following AppSetting key to your web.config (making sure to replace the UA-XXXXXXX-X with your unique tracking code key generated in your Google Analytics control panel):

<add key="GoogleAnalyticsKey" value="UA-XXXXXXX-X"/> 

Finally add the following to your BasePage constructor:

if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["GoogleAnalyticsKey"]) && !Page.IsClientScriptBlockRegistered("GoogleAnalytics")) 
    Page.RegisterClientScriptBlock("GoogleAnalytics", string.Format(GOOGLE_ANALYTICS_JAVASCRIPT, WebConfigurationManager.AppSettings["GoogleAnalyticsKey"])); 

Now run your site! What the above code does is check if an AppSetting called GoogleAnalyticsKey exists, if it does it registers a client script block containing Google Analytics new tracking code (javascript) adding your unique tracking code pulled from the AppSettings key.... bingo! Now you can re-use your BasePage on other projects/sites and so long as you remember to add the relevant GoogleAnalyticsKey to the AppSettings you'll have Google stats.

Some of you might wonder why i'm using obsolete methods (Visual Studio will complain and tell you to use Page.ClientScript..... instead) but this is because i've had issues whereby the IsClientScriptBlockRegistered would return incorrect results - namely false every time, so until Microsoft fix it (probably in .NET 3.5) I'll continue doing it old school.

Tags:

C#

Comments

7/31/2008 11:06:49 AM #

Nice little bit of code.

I was wondering how come you don't just put the Google Analytics code into the master page?

Chris Hardy |

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar