Google Analytics and Flex using ExternalInterface

A big issue for people creating flash sites is getting the site to work well with Google Analytics. “The page doesn’t refresh. How can I track the clicks?”

Well, it is actually very easy. If you look at the trace script Google Analytics gives you to add to your HTML code you can find a call to a method that actually records the event. This method is simple to call using JavaScript.

I have solved it like this in my latest Flex App (which is a public site). NOTE: This is for the new trace code version.

1. Paste the Google Analytics trace code as usual just before the </BODY> tag.
Check your Google Analytics account for the correct code.

2. See to it that your embedded flash works with ExternalInterface.
This can be a bit tricky, but in my experience the things that do the trick are to change allowScriptAccess to always and inside the Flex App call a custom JavaScript function on creationComplete like so: ExternalInterface.call(‘initFlash’). In my html this initFlash function creates a variable reference to the embedded flash. This sort of “creates the connection” between them. I’m not sure why this is so, but for me it works, so I’m happy with that. If there is a need I would be glad to create a more thorough tutorial on the use of ExternalInterface. Just let me know.

3. Create a custom JavaScript that passes the URL you want to register to the Google Analytics script.
This is not necessary, but I have found it easier to work with, as you don’t need to edit you call from inside of Flex if something changes in the Google code or such.

function trackURL(url)
{
    pageTracker._trackPageview(url);
}

4. Call your custom javascript from within Flex.
I created a static class for this. (I love static classes). I named it Analytics.as and placed it in the root source folder in the Flex App. It looks like this. All it does really is call the JavaScript using ExternalInterface, but putting it within a static class lets you call it from anywhere in your application without having to pass on references to this or that object or function.

package
{
   public class Analytics
   {
      import flash.external.ExternalInterface;

      public static function track(url:String) : void
      {
         ExternalInterface.call("trackURL", url);
      }
   }
}

And anywhere in your app write:

Analytics.track('/path_to_tha_page_you_want_to_track/');

(NOTE: You have to start your path with a slash).

There you go. It now should track the URL:s you want and give you nice statistics.

5 thoughts on “Google Analytics and Flex using ExternalInterface

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>