Monday, September 27, 2010

Using Google Analytics in Silverlight Event Tracking

Recently we had a requirement to track event(button click) in Silverlight application using google analytics. I have done research on Google Analytics as well as Microsoft Silverlight Analytics Framework(MSAF). I read that MSAF does not work with Silverlight 3 so I decided to go with Google Analytics. Following is the code we have to use for event tracking.

IN SILVERLIGHT HOST PAGE (e.g.testGA.aspx)
[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("YOUR PROFILE ID E.G. UA-XXXXXXX-1");
pageTracker._trackPageview();
}
catch (err) { }

[/script]
[script type="text/javascript"]
function trackEvent(category, action, label) {
pageTracker._trackEvent(category, action, label);
}
[/script]

IN SILVERLIGHT XAML PAGE (e.g. testGA.xaml.vb) ON BUTTON CLICK (if you want to track that how many users have clicked button )

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
HtmlPage.Window.Invoke("trackEvent", New Object() {"testGAEventTracking", "AddtoCart", "Click"})
End Sub


Note - Please replace [ with < and ] with > for script block

No comments: