Disclaimer: I taught myself to program without the aid of formal instruction, and am therefore a bit rough on some basic terminology, amongst other things. While the solution below works, if anyone knows of a better way to accomplish this, I’d love to know of it.
I’m working on an update to the video player at work. One of the requested features is the ability to track viewing data in Google Analytics. I created a functional proof of concept last October that involved a call to a javascript file linked to the page. This was recently re-visited as part of a larger site re-design and didn’t work, forcing me to go back to the drawing board. Turns out, Google created a Widget that will let you track Analytics Data directly through Actionscript called ‘GAforFlash.’ You can find official documentation and a download link from the following page:
The proof of concept that I created according to the documentation, or more to the point, by cutting and pasting their code into a new Flash file worked perfectly. The problem, which I could not find a documented solution anywhere on the web, was how to get this to work in a class based environment. Putting the call anywhere other then the first frame, or the top level class file produced an error(#1009). After a few hours of beating my head against the wall, and a series of test environments, I decided to apply the same logic to how global variables are constructed in Flash, and came up with the following solution:
By default, all of my Actionscript 3 work starts with a central class file called “main”, which is used to call a series of starting-state classes that handle matters like global variables, directory structure, preloaders, ect…. All classes that call upon other more program-specific class files, none of which can use the Analytics or AnalyticsLibrary widgets without causing the 1009 error. So I decided to try to declare the Analytics Tracker in the main class file, and attach a reference to it for every class that needs some form of tracking data. It worked perfectly!
Documentation:
In your top level class file, import the necessary Flash files in the package declaration:
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.GATracker;
Declare the tracker in the class declaration:
public static var tracker:AnalyticsTracker;
Then set up your tracker in the function declaration:
tracker = new GATracker( this, “UA-******-**”, “AS3″, false );
Now that it’s set up, in any subsequent class where you need to track analytics data, simply import the main class in your package declaration, and add ‘main.’ to the line calling the tracker. ex:
main.tracker.trackEvent(“-Video-”, “Video Player Loaded: “+Object(e).data, “Option”, 1);
Now I can track any event that I want! I just need to modify the code to include variables that track the title of the video in question!