My app reads an (html) file from my website, and I would like to track accesses to that file using Google Analytics. As the GA Javascript does not get executed when reading the file, it is not tracked. Is there a way to trigger GA directly from code or alternatively, to execute the Javascript from a .NET app without adding a bunch of dependencies?
Google Analytics works by making a webrequest through javascript back to Google's server. If you want to do this programmatically, you just have to make this web request yourself. I would use Fiddler or FireBug to capture what the request looks like when you load the page in your browser. Then you can use that same URL in your .Net app.
Google Analytics provides two way to track custom actions, events, or whatever you deal with. In your case, the trivial solution is to generate a virtual pageview for the HTML file your application reads in. Call the appropriate JavaScript function:
pageTracker._trackPageview("/Foo.html");
This way every time Foo.html is processed, a pageview will be generated for it as same as it would be a normal query to your application.
If you'd like to distinguish these Foo.htmls from the normal pageviews, GA has a nice feature called Event Tracking then you should take a look at.
I ended up using the WebBrowser component to load the .html file, and thereby trigger the GA tracker. The WebBrowser component executes the embedded JavaScript.
using (WebBrowser wb = new WebBrowser())
{
wb.Url = new Uri(@"mytrackingpage.html");
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
}
Now all I have to do is to add some errorhandling, get rid of the ugly DoEvents and move the WebBrowser to a separate thread.
I have recently released a .net library that allows you to natively log a page view with Google Analytics through code. It is released as open source under GNU so all that is required is proper attribution.
You can get the library here: http://www.diaryofaninja.com/projects/details/ga-dot-net
example usage of the API:
GooglePageView pageView = new GooglePageView("My page title",
"www.mydomain.com",
"/my-page-url.html");
TrackingRequest request = new RequestFactory().BuildRequest(pageView);
GoogleTracking.FireTrackingEvent(request);
There is also a built in HTTP Handler that allows you to fire tracking events by simply including a tracking pixel on the page:
<img src="/tracker.asmx?domain=mydomain.com&pagetitle=My%20Page%20Title&url=/my-page.aspx" />
Alternatively you can use jquery to track links within a page using Google Analytics (zip, jpg, etc) - blogged about it a while ago here: