Skyline Groningen
Toegevoegd op

Using Google Analytics with a Flex application

For a recent project I was doing in Flex I wanted to use Google Analytics. At first I thought this would be hard to do, but it proved to be quite simple. Here's how to do it. In a 'normal' web page you would use GA like this: Afbeelding verwijderd. When the page is loaded a call to urchinTracker() is made with no parameters. This sends the url of the page to GA. The trick to using GA with Flex is to call the urchinTracker function from within the Flex application. For this the scripts have to be included in the surrounding html wrapper file. Note: if you are not using your Flex application with a browser but with Flash player this solution will not work. I'm using FlexBuilder for my Flex projects. FlexBuilder automaticly makes a wrapper html. This wrapper html is based on the index.template.html file. Therefore I added the scripts to this template file. To call the script from within your Flex application you can use the ExternalInterface component like this: Afbeelding verwijderd. This script first checks if the external interface (i.e. browser) is available. If so it calls the javascript function urchinTracker in the surrounding wrapper and passes a string as a parameter. Using this string you can differentiate the actions the user takes using your application in the GA reports. Take a look at the following examples. Afbeelding verwijderd. I have to admit that two buttons doing nothing but alerting GA that they have been clicked may not be the most useful functionality in your application but it serves well as an example. That's it! Now every time a user clicks one of these buttons it should show in your GA reports. Testing that it really works may actually be harder than the above coding. I ran into a few problems. First the GA script will not work unless they are called from a real domain. Testing from say http://localhost/myapp or file://mypath/myapp will not work. The same goes for using a testserver like http://mytestserver/myapp. Using http://mytestserver.net/myapp can work. Secondly it may take several hours (up to 24) before the events show up in the reports. Doing a little test, viewing the reports, tinkering a little and doing another test is therefore not a great way to go. To see if the script really sends something to GA I check the headers. Here's a blog that shows you how to do that. The last problem I had was something really stupid. I did some tests and checked the headers. After a few hours nothing showed up in the reports. After a day still nothing showed up. It turned out that in our GA preferences we activated a filter to exclude everything generated by our own IP address. I then did a test from my home pc and then it showed up in the report.