Today I've been consolidating UserControls that I've found myself using in one EPiServer project after another into a nice Server Control library. One such control that gets used on every site (even non-EPiServer ones) is one which adds the Google Analytics JavaScript code to the page. I decided this would be the first UserControl to migrate.
Firstly I created a constant GoogleAnalyticsJavaScript which holds the JavaScript string to be added to the page. The only change I needed to make was to dynamically add the unique Google Analytics tracking code that was generated specifically for my domain. I could have stored this as a dynamic property in EPiServer, but decided that since it would hardly change, if ever, that the AppSettings would be a more suitable place. (This also makes the code more portable - sorry EPiServer!)
So I simply overrided the CreateChildControls and perform a quick check to make sure that there is a AppSetting with a Key of GoogleAnalyticsKey and that the script hasn't already been added to the page. Next i had to register it as a startup script (I chose startup script so it would be rendered near the end of body tag - perfect for situations where I want to add specific custom Google tracking to links within my page - I.e. downloads, RSS feeds etc. Registering a standard script block would appear at the top of the body meaning that custom link tracking wouldn't work).
The code listing is shown below:
public class GoogleAnalytics : InteraktingServerControl
{
public const string GoogleAnalyticsJavaScript = @"
<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>";
protected override void CreateChildControls()
{
//Make sure the Google Analytics key is set in the AppSettings
//Also make sure the script hasn't been registered already
if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["GoogleAnalyticsKey"])
&& Page.ClientScript.IsStartupScriptRegistered(typeof(GoogleAnalytics), "GoogleAnalyticsKey" + ID))
{
Page.ClientScript.RegisterStartupScript(
typeof(GoogleAnalytics),
"GoogleAnalyticsKey" + ID,
string.Format(
GoogleAnalyticsJavaScript,
WebConfigurationManager.AppSettings["GoogleAnalyticsKey"]
)
);
}
base.CreateChildControls();
}
}