There are many instances where you might need to implement Google Analytics tracking in your Flash or Flex project. A while back I integrated Google Analytics in a Adobe AIR application which was specifically built for social media marketing.

To use Google Analytics you have to create an account on Google Analytics and then create a website profile. Once a website profile is created Google Analytics will provide a UA code which is a unique ID that it uses to send and store metrics data.

Google provides an open source ActionScript 3 API for Google Analytics data collection which can be downloaded from http://code.google.com/p/gaforflash/. This allows you to track up to 5 million events and pageviews per day without any restriction, you can have more than 5 million requests only if Google approves.

After creating a profile on Google Analytics, you have to install GaforFlash on your system. The main component required in ActionScript development platform is the AnalyticsLibrary component that needs to be installed in the /Configuration/Components folder.

I am a huge fan of OOP development so I will always implement Google Analytics as an external class that I could invoke wherever and whenever I like. Below is a simple class that you could use to start tracking events and pageviews.

package com.elevatelocal.model{
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.GATracker;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;

public class AnalyticsTrackToday extends MovieClip {

private var _stageAccess:MovieClip;
private var _keywordTracker:String;

private var tracker:AnalyticsTracker;

public function AnalyticsTrackToday(getStage:MovieClip) {
tracker=new GATracker(getStage,"UA-15476449-1","AS3",false);

_stageAccess=getStage;

}

public function onQuery(getKeywords:String) {
_keywordTracker=getKeywords;

if (_keywordTracker!=null) {
tracker.trackEvent("search queries","keywords",_keywordTracker);
trace(tracker.trackEvent);
}
}
}
}

To initiate the tracking process, 4 parameters have to be passed.

  • Stage
  • UA Code
  • Tracking Mode
  • Test mode

In my implementation the Stage is only accessible in the document class so I used a work around to get Stage property. The constructor for AnalyticsTrackToday (see below) class takes a MovieClip as a parameter; any MovieClip passed from the document class has access to Stage. Therefore an instance of the Top Menu has been passed as a parameter in this case.

tracker=new GATracker(getStage,”UA-15476449-1″,”AS3″,false);

Once this is setup, the application can invoke the trackEvent method to send data to Google Analytics like below

var _AnalyticsTrackToday:AnalyticsTrackToday=new AnalyticsTrackToday(_topMenu);
var _trackQueries:AnalyticsTrackToday=new AnalyticsTrackToday(_topMenu);
_trackQueries.onQuery(_searchField.text);