Get Current URL and Query String Parameters to Flash | Tutorial

Update: please see the newer tut talking about getting the current url, query string vars and more with as3

Overview

This tutorial / how to / example will show how to get the current url from the browser to flash, and even how to get the query string parameters from the url into actionscript using ExternalInterface.
It has been a dilemma for many people to get this information into flash across browsers and without having to rely on flashvars or javascript, but to just have it work.
I wrote a post on it earlier, although it seemed it wouldn’t play nice with Internet Explorer IE, I later realized that it was only because of the way my blog is configured to embed flash. The call ExternalInterface.call(“window.location.href.toString”); or even ExternalInterface.call(‘eval’, ‘window.location.href’); which basically do the same thing.
This can be taken even further and we can read the query string, which, if you don’t know what that is, is the data contained in the url. The data is sent as paired strings, the key and the value. So, for example I could have a url http://example.com/index.html?var1=one&var2=two&var3=three. The question mark separates the actual url path from the query string. So following the ‘?’ we see three variables: var1, var2 and var3, and their corresponding values: one, two and three. They are seperated as pairs with an ampersand (&) and then the key and value are seperated by an equals sign (=). So it goes url?key=value&key=value&key=value…
Once we pass the complete url into our swf, it’s pretty easy to parse the keys and corresponding values.

Steps

  1. Rather than use url with ExternalInterface.call(“window.location.href.toString”); implement the QueryString class make a new QueryString This will do most of the work for you: var myPath:QueryString = new QueryString();
    1. Upon creation of the QueryString object the class reads the parameters automatically by parsing the parameters after the ‘?’ and delimiting on the ‘&’. So you get var1=one and var2=two
    2. Set up each parameter (key) as a variable in the parameter object of the QueryString class assigning it’s value to that variable.
  2. Access your values as myPath.parameters.var1 and myPath.parameters.var2
  3. unescape() your values to make the usable, unless you need them to be encoded or course. Unescape decodes the string from URL-encoded format (converting all hexadecimal sequences to ASCII characters). If your parameter had been some funky encoded string like var4=this+stuff%3E%22%28%29%3F, after you unescape(myPath.parameters.var4) you get: this stuff>”()?.

Example

get url params screenshot
Here’s a working example. This link has the parameters appended to it following the question mark ‘?’ and separated with an ampersand ‘&’ like all query string parameters. I have one for myName (Circlecube) another for myText (Jo Jo is a monkey) which are both pulled out and put into their own text box after they are unescaped, and then there are a couple more parameters just to show, the aNum (3013), anotherParam (more), and ref (https://circlecube.com/circlecube/…)

Special thanks to Abdul Qabiz example. I rewrote it for as2 so it would work with some flash projects I’m working on.

I use the new swf object 2 to embed the swf. Go get it here: swfobject

Actionscript:

The actionscript layer of the swf
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
import flash.external.*; //so we can use externalInterface
import QueryString.as; //so we can use the QueryString Class//make a new QueryString named myPath
var myPath:QueryString = new QueryString();
assignVariables();

//custom function to handle all the query string parameters
function assignVariables() {
//if myName parameter exists
if (myPath.parameters.myName) {
//assign it to the text of the myName text box
//unescape() will translate/unencode the url characters
myName.text = unescape(myPath.parameters.myName);
}
if (myPath.parameters.myText) {
myText.text = unescape(myPath.parameters.myText);
}
if (myPath.url) {
//get the complete url (including any parameters)
thisUrl.text = myPath.url;
}
recurseTrace(myPath.parameters, ” “);
}

//function to recursivly print objects in heirarchy as string
//so we get all parameters no matter what the key traced into
//the allParams text box.
function recurseTrace(info:Object, indent:String) {
for (var i in info) {
if (typeof info[i] == “object”) {
traceParams(indent + i + “:”);
recurseTrace(info[i], indent + ” “);
}
else {
traceParams(indent + i + “: ” + info[i] + “\n”);
}
}
}

function traceParams(traceMe:String) {
allParams.text += traceMe;
}
[/cc]

The QueryString.as class for as2
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
class QueryString {
//instance variables
var _queryString;
var _all;
var _params:Object;

public function QueryString() {
readQueryString();
}
public function get getQueryString():String {
return _queryString;
}
public function get url():String {
return _all;
}
public function get parameters():Object {
return _params;
}

private function readQueryString() {
_params = {};
try {
_all = ExternalInterface.call(“window.location.href.toString”);
_queryString = ExternalInterface.call(“window.location.search.substring”, 1);
if(_queryString) {
var allParams:Array = _queryString.split(‘&’);
//var length:uint = params.length;

for (var i = 0, index = -1; i < allParams.length; i++) {
var keyValuePair:String = allParams[i];
if((index = keyValuePair.indexOf(“=”)) > 0) {
var paramKey:String = keyValuePair.substring(0,index);
var paramValue:String = keyValuePair.substring(index+1);
_params[paramKey] = paramValue;
}
}
}
}
catch(e:Error) {
trace(“Some error occured. ExternalInterface doesn’t work in Standalone player.”);
}
}
}
[/cc]

Download

Here’s a zip file containing the sample files, the QueryString Class file, and even the swfobject javascript file.
getURLParams.zip

Interactive Spin Actionscript Tutorial

I have been thinking of different interactions that are possible with objects. If you’ve read this blog at all you’ll know that I’ve played with physics and gravity and throwing balls and bouncing balls and all sorts. But I hadn’t wrapped my head around an interactive spinner. I know it’d be easy to make a slider or something that would apply a spin to an object, but this just isn’t interactive enough for me.

Circle with slider to rotate and button for random spin:

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/03/spin.swf” width=”500″ height=”300″ targetclass=”flashmovie”]Get Adobe Flash player

[/kml_flashembed]

This attempt at spinning is ok. I mean, it spins the object and it even glides to a stop if you press the button for a random spin… But it’s just not intuitive and not fun. But if you want this, here’s how I did it.

Actionscript:

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
drag = .96;
speed = 0;

slider.handle.onPress = function() {
spinning = false;
//drag along the line
this.startDrag(true, slider.line._x-slider.handle._width/2, slider.line._y-slider.handle._height/2, slider.line._width-slider.handle._width/2, slider.line._y-slider.handle._height/2);
}
slider.handle.onRelease = slider.handle.onReleaseOutside = function() {
this.stopDrag();
}
_root.onEnterFrame = function() {
if (spinning) {
//apply the speed to the rotation
knob._rotation += speed;
//recalculate speed
speed = speed*drag;
//if speed gets unnoticeably tiny just set it to 0
if (Math.pow(speed, 2) < .0001) {
speed = 0;
}
}
else {
//set the rotation from the slider position
knob._rotation = slider.line._x + slider.handle._x + slider.handle._width/2;
}

//spit out feedback continuously
feedbackr.text = knob._rotation;
feedbackaccr.text = speed;
}
spinner.onRelease = function() {
//find a random speed
speed = (Math.random()* 50) – 25;
spinning = true;
}
[/cc]

I want to grab it and spin it though. I want to apply the same principles from physics, like acceleration and friction as forces to the object, so I can grab to spin and release to watch it glide gracefully to a stop. I’ve been thinking about this and how I’d have to use trigonometry and stuff to do it. One day I finally had the time and tried it out. It took me a minute but I figured out that what I needed was arctangent. So (with pointers from jbum, thanks Jim!) I came up with this:

Interactive grab-able circle to spin and twirl:
[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/03/interactivespin.swf” width=”500″ height=”300″ targetclass=”flashmovie”]Get Adobe Flash player

[/kml_flashembed]

This one is much more interactive and intuitive. I really think this is because there are no sliders or buttons, no controls, just an object to interact with. It’s much more like real life!

Steps:

In order to make a grab and spin object
1. You have to know where you grab. The user clicks on the shape (knob) and you must figure out what degree or rotation point they have started at. (atan2)
2. As the knob is clicked and the mouse moves (dragging), calculate new rotation by mouse position
3. When mouse is released figure out the current speed of rotation and apply it to the knob with friction, so it can be thrown and spun in that way. (Of course this is optional, if you just want to spin it when the mouse is down you’re done at step 2)

Actionscript:

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
damp = .96; //friction
r = 0; //rotation
accr = 0; //speed of rotation

knob.onPress = function() {
dragging = true;
//find mouse y coordinate in relation to knob origin
a = _root._ymouse – knob._y;
//find mouse x coordinate in relation to knob origin
b = _root._xmouse – knob._x;
//using arctangent find the spot of rotation (in degrees)
oldr = Math.atan2(a,b)*180/Math.PI;
}

knob.onRelease = knob.onReleaseOutside = function() {
dragging = false;
}

knob.onEnterFrame = function() {
if (dragging) {
//find mouse y coordinate in relation to knob origin
a = _root._ymouse-knob._y;
//find mouse x coordinate in relation to knob origin
b = _root._xmouse-knob._x;
//using arctangent find the spot of rotation (in degrees)
r = Math.atan2(a,b)*180/Math.PI;

//use current rotation and previous rotation
//to find acceleration
//averages the acceleration with the
//previous acceleration for smoother spins
accr = ((r – oldr) + accr)/2;
//apply the acceleration to the rotation
knob._rotation += accr;
//remember current rotation as old rotation
oldr = r;
feedbacka.text = a;
feedbackb.text = b;
}
else {
knob._rotation += accr;
//apply friction to acceleration force
//and if acceleration gets tiny, just set it to zero
if (Math.pow(accr, 2) > .0001 ) {
accr *= damp;
}
else{
accr = 0;
}
}
//spit out feedback continuosly
feedbackr.text = knob._rotation;
feedbackaccr.text = accr;
}
[/cc]

I commented the code to explain what is happening, if you need more just post a comment. Let me know if you find this useful and what you end up making with it.

Downloads:

spin.fla and interactiveSpin.fla

Local Connection Actionscript – Communicate between seperate Flash files | Tutorial

Overview:

Local Connection
Communication between two separate flash files placed on the same page (or even running simultaneously on one machine) is a nice way to spread a project out. You can send variable, call functions, pretty much do anything in one swf from another. Easiest case use would be a navigation menu set up in one flash file to control the other one containing the content. I’ve made an example here showing how to send text from one to another. I’ve done it both directions here. Send text from the red swf to the blue swf, and from mr. Blue you send to the red flash file. I have named the flash functions in actionscript accordingly (or tried to, now I notice a few places I misspelled receive, ‘i’ before ‘e’, right? oh yea, except after ‘c’)…
Anyways, try out the example here, I made it a little easier by putting a keyListener on ‘Enter’, so you don’t have to actually press the send button. Didn’t realize it before, but this is like a chat app built in flash! So go ahead and chat with yourself to prove that it works!

Execute actionscript in one swf from another! Inter-swf communication.

Example:

Type here to send Red text to Blue flash file
[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/03/localConnectionRed.swf” width=”550″ height=”400″ targetclass=”flashmovie”]Get Adobe Flash player

[/kml_flashembed]

And see it received here, and go ahead and send some back to Red.
[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/03/localConnectionBlue.swf” width=”550″ height=”400″ targetclass=”flashmovie”]Get Adobe Flash player

[/kml_flashembed]

Actionscript:

Red:
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
// Receiving
//create a local connection for reciept of text
var receiving_lc:LocalConnection = new LocalConnection();
//function called from other swf
receiving_lc.recieveBlueText = function(textRecieved:String) {
feedback.text += textRecieved+”\n”;
};
//receive connection of specified name
receiving_lc.connect(“fromBlue”);

//Sending
sendButton.onRelease = function() {
//create local connection for sending text
var sending_lc:LocalConnection = new LocalConnection();
//put text from input into a var
var textToSend = inputText.text;
//send through specified connection, call specified method, send specified parameter
sending_lc.send(“fromRed”, “recieveRedText”, textToSend);
//set the input empty
inputText.text = “”;
}
[/cc]

Blue:
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
// Receiving
var receiving_lc:LocalConnection = new LocalConnection();
receiving_lc.recieveRedText = function(textRecieved:String) {
feedback.text += textRecieved+”\n”;
};
receiving_lc.connect(“fromRed”);

//Sending
sendButton.onRelease = function() {
var sending_lc:LocalConnection = new LocalConnection();
var textToSend = inputText.text;
sending_lc.send(“fromBlue”, “recieveBlueText”, textToSend);
inputText.text = “”;
}
[/cc]

And the code to listen to the ‘enter’ key(this is in both files):
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
//Enter button to send
var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
if (Key.getCode() == “13”) {
sendButton.onRelease();
}
};
Key.addListener(keyListener);
[/cc]

Download Source:

localConnectionRedBlue.zip

Free IQ Player integrates Google Analytics for Video

As announced, the Free IQ Media Player now incorporates Google Analytics with it’s custom flash video player. Simply put, users may upload their own content (or even use anyone else’s content that is on Free IQ), embed it on their own sites and then view the tracking/logging/usage/analytics/metrics it their own Google analytics account. You don’t have to do anything- the player will do it automatically, but if you don’t have google analytics installed on your site, nothing happens. So go ahead and sign up, it’s free and very useful.

This works with both versions of Google analytics tracking code. Recently Google updated the code they give users to enhance the functionality of the analytics they give you in their reports. Some have voiced concern about whether they can update to the new code and still use the Free IQ video tracking, now the answer is yes! This new updated player works with the new Google Analytics Tracking Code! Others have voiced a concern that they aren’t ready to update the Google code on the rest of their site yet, this is not a problem either. The Free IQ Player works with either version of the GATC (Google Analytics Tracking Code). It would even work with both… say you had a site with some old code and some new code, the player knows and will tell Google what people are doing with this player on your site.

free IQ google analytics search filter screenshot
To see the report, go to your google analytics account, click on ‘Content’, and then ‘Top Content’. This page shows you the most viewed pages on your site. You can filter the report by typing in the box under the list of urls. Find the ‘Find Url’ box (be sure ‘containing’ is selected in the drop-down) and type ‘freeiqvideo/’. Press ‘go’ and you should see all the analytics for the Free IQ player on your site! All the analytics from the player start with ‘freeiqvideo/’ in the url path and we’ve organized all the analytics into three different types: Video, Actions and Navigation. Every time someone does any of these things on your site, google analytics will log a pageview to a certain page. This certain page changes and depends upon what the user did exactly. When a user visits your site and begins to watch a certain video called ‘My Cool Video’, google analytics logs a pageview to ‘freeiqvideo/playstart/mycoolvideo! Notice that the title of the video is incorporated into the report, this helps determine which video is more popular and such. The title of the video is the title you give Free IQ upon uploading your content and can usually also be found at http://freeiq.com/mycoolvideo

This information can be very helful as you think about which video to place or keep on your site, and even where to put it. You can also see how many times the video was finished (freeiqvideo/playcomplete/mycoolvideo). This can be very useful to help you determine if your video is too long, too boring, or on the other end very engaging- it’s essentially your video bounce rate.

Other than video tracking, the Free IQ Player also logs to google analytics actions users have with the player itself. The Free IQ Player enables users to share your content with others. There are interactions with the player for users to email a link to their friends about the content they are watching, get html codes to embed that content onto their own site, and even share the content with any of a number of social bookmarking sites! If someone were to use the Free IQ Player to link to your content through a popular del.icio.us the report would log a pageview at ‘freeiqvideo/PlayerInteraction/SharedVideo/delicious/mycoolvideo’! You will see which bookmarking service was used and what content was bookmarked! You will know what users are doing with your content!

free IQ google analytics player Navigation
And lastly you can see how users navigate through the embedded Free IQ Player. Inside the player, users are presented with information about the content they watch. All this information is organized into tabbed windows. Every time a user view’s this information, the player logs to google analytics a page view. These logs are independent of the content, so the url reported does not include the video Title as before. An example is a user views the author window is: /freeiqvideo/PlayerNav/WindowSelected/author.

Here is the breakdown of all the logging from the Free IQ Player to Google Analytics:
Video Tracking:
Play Started: /freeiqvideo/playstart/mycoolvideo
Play Completed: /freeiqvideo/playcomplete/mycoolvideo

Interactions:
Embed Codes Copied: /freeiqvideo/PlayerInteraction/EmbedCodesCopied/mycoolvideo
Email Sent: /freeiqvideo/PlayerInteraction/EmailSent/mycoolvideo
Bookmark: /freeiqvideo/PlayerInteraction/SharedVideo/bookmarkingService/mycoolvideo

Navigation:
Author Tab Selected: /freeiqvideo/PlayerNav/WindowSelected/author
Playlist Tab Selected: /freeiqvideo/PlayerNav/WindowSelected/playlist
IQPON Tab Selected: /freeiqvideo/PlayerNav/WindowSelected/iqpon
Share Tab Selected: /freeiqvideo/PlayerNav/WindowSelected/share
Email Tab Selected: /freeiqvideo/PlayerNav/WindowSelected/email
Embed Tab Selected: /freeiqvideo/PlayerNav/WindowSelected/embed

This is the list of current integration with Google Analytics from the Free IQ Player. If you have any questions or requests, feel free to comment here or contact Free IQ.

How to convert DVD to iPod mp4 Video? PQ DVD to iPod Video Converter Tutorial.

Detect Flash Player Version | Actionscript based detection method (as2)

looking for this in as3!? look no more Detect Flash Player Version | Actionscript based detection method (as3)

Overview

Recently I had a requirement that I had to detect which version of the flash player was currently installed. This is a normal thing, we do it all the time when embedding flash into html, we detect which version of the player is installed and if the user has an old version they are invited to upgrade…

But what about finding the flash version from within flash? An actionscript based detection method? I hadn’t ever thought about doing that…

It turns out it is very simple. From adobe I found the flash detection kit. Which had a lot of code I didn’t need. I only want to know what version of the player is running, not forward to upgrade sites and redirect… So I made this little testing file to save and share what I learned:

Steps

Internally flash knows it’s version number as $version. So to read it we must evaluate that variable.

eval(“$version”);

This returns a string, 3 letter operating system, a space, and then the version number as four numbers seperated with commas.
I display the $version and to split it out I split the string on the space, and then split the version number with the comma delimiter and display them all.

Example

Here’s what mine is (gif):

version detection actionscript gif

And here’s what yours is (swf):
[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/03/flashversiondetectionactionscriptmethod.swf” width=”160″ height=”160″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

Actionscript (as2)

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
version = eval(“$version”);

//The operating system: WIN, MAC, LNX
var osType;
//The player version.
//The latest as of December ’07: 9,0,115,0
var majorVersion; //9
var majorRevision; //0
var minorVersion; //115
var minorRevision; //0

vers.text = version;

osArray = version.split(‘ ‘);
osType = osArray[0];

versionArray = osArray[1].split(‘,’);
majorVersion = versionArray[0];
majorRevision = versionArray[1];
minorVersion = versionArray[2];
minorRevision = versionArray[3];
[/cc]

Download

Here’s the source fla file: flash version detection actionscript method

Let me know how and if you find this useful

Distance Formula in Actionscript Tutorial | Pythagorean theorem

Overview

To find the distance of any two points on an axis is easy, just subtract them. But what about when you have to find the distance of something not on the axis (a diagonal)? Find the distance between any two points with the Pythagorean theorem. This is an old problem we can look to history and find the Pythagorean theorem and Pythagoras, the Greek we’ve named this after. His theorem states that ‘In any right triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).’
pythagorean img

You may remember it as the formula you memorized in geometry or algebra class ‘a squared plus b squared equals c squared’
a^2 + b^2 = c^2
pythag equ

Okay, but how does that help in flash? You want to find the distance between point a and point b. Well c would be the distance between the two points. We know the formula, solving for c.
c = square root of (a^2 + b^2).
pythag equ 2
c = Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2));
Math.sqrt()
is the square root function, so Math.sqrt(4)=2.
Math.sqrt(x) computes and returns the square root of x.
Math.pow() is the power function, so Math.pow(4, 2)=16 (4 squared). Math.pow(x, y) computes and returns x to the power of y.

You say I remember using this for triangles and stuff, I just want to know the distance between two points, there’s no triangles.
Well, there actually is a triangle we can draw. Go from your first, along an axis (this makes one side), and the other point, along the other axis (this is another side), and you’ll see that the distance you’re looking for is the third side of the triangle (the hypotenuse).

Example

Here’s a quick interactive flash file to show the idea.
[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/02/distance.swf” width=”500″ height=”500″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

Actionscript

[cc lang=”actionscript” tab_size=”2″ lines=”40″]
xmid = Stage.width/2;
ymid = Stage.height/2;
a = _root._ymouse-ymid;
b = _root._xmouse-xmid;
c = Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2));
feedbacka.text = Math.round(a);
feedbackb.text = Math.round(b);
feedbackc.text = Math.round(c);
[/cc]

Download

As usual, here’s the source flash file (flash 8 compatible) to take a look: distance.fla

CSS and HTML WYSIWYG in Flash | Open Source Example

Overview:

Using what I learned with the Actionscript Javascript Communication Tutorial, and pushing it a little further I’ve set up this example of how flash renders html and css. This is basically a wysiwyg (What you see is what you get) html editor! Natively flash only handles some html and css. Many people have enhanced it’s capabilities with projects and Classes, but I made this to show what is accepted by default as far as html and css is concerned. I know there are specs and many lists about what will work, but to me the best way to know if my code will work is to try and see…
I’ve made this app so if I have a question, I just paste in my html/css and send it to the swf to see it rendered live. This saved me a few headaches, so I thought other might enjoy it as well… So here it is.

Example:

Render your own html and or css in flash. htmlToFlash.html
Here is the flash rendering of some dummy text as html with css applied
htmltoflash thumb

Here’s the html interface where I paste in the html and css.
htmltoflash thumb 2
Each supported css property has a corresponding actionscript property, but the naming convention is a little different for css in actionscript. Each actionscript property name is derived from the corresponding CSS property name; the hyphen is omitted and the subsequent character is capitalized. So for example: ‘font-weight’ becomes ‘fontWeight’.

Download:

Here’s the open source files if you want to get your hands dirty.

Let me know if you improve this or even have any questions about it!

Again, note there are only certain HTMl and CSS supported by flash, follow the links for more info.
HTML supported by Flash and CSS supported by Flash

Actionscript Javascript Communication | ExternalInterface call and addCallback Tutorial

UPDATE: there’s a newer post about this same thing (actionscript javascript communication – but in as3)! I encourage you to check it out!

Overview:

Using ExternalInterface.addCallback() we can expose an actionscript function and make it available to javascript. This would be helpful to have your webpage with embedded flash communicate to your flash swf file and even control it with javascript! Say we wanted to have buttons in the html page that would control an object in the flash. Communication is a two-way road so wouldn’t it be great to be able to go the other way as well, you can! That is the main function of ExternalInterface! In this example/tutorial I will explain both directions of communication with flash and javascript! Communication between flash and javascript isn’t just a myth or mystery!

Steps:

  1. Be sure to import flash.external.*;
  2. Set up the javascript to actionscript lane of your communication road. (ExternalInterface.addCallback(methodName, instance, method);)
  3. Write your javascript function.
  4. Set up the actionscript to javascript lane. (ExternalInterface.call(functionNameInJavascript);)

We will follow the text’s journey on our road of communication…

The One way: I type in ‘Johnny Appleseed’ in the html text box and press the Send Text To Flash button. The onclick javascript event finds the flash element and calls it’s function (sendTextFromHtml) and then clears the text in the html box. This function has been set up and is exposed to javascript (in actionscript lines 4-7) with the methodName ‘sendTextFromHtml’ while the method it calls is recieveTextFromHtml() in the actionscript. So ‘Johnny Appleseed’ is received as the parameter of the recieveTextFromHtml() function and is assigned to the text of the theText text box.

And back: Now I delete ‘Johnny Appleseed’ since he’s only a fable and enter ‘Paul Bunyan’ in the swf text box and press the Send From Flash to Javascript button. This calls the onRelease function associated with this button. ExternalInterface.call calls the ‘recieveTextFromFlash’ function in the javascript of the page and passes ‘Paul Bunyan’ as the parameter. The javascript function finds the html text box using getElementById() and assigns the parameter to the value of that text box!

This technique will even work if you’re not sending folklore character down the road.

Example:

View the live example here: ActionscriptJavascriptCommunication.html

NEW live example with swfobject2 works in IE! ActionscriptJavascriptCommunication2.html

Actionscript Javascript Communication thumbnail
Actionscript:
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
import flash.external.*;

//Set up Javascript to Actioscript
var methodName:String = “sendTextFromHtml”;
var instance:Object = null;
var method:Function = recieveTextFromHtml;
var wasSuccessful:Boolean = ExternalInterface.addCallback(methodName, instance, method);

//Actionscript to Javascript
//ExternalInterface.call(“recieveTextFromFlash”, _root.theText.text);

function recieveTextFromHtml(t) {
_root.theText.text = t;
}

_root.button.onRelease = function() {
ExternalInterface.call(“recieveTextFromFlash”, _root.theText.text);
_root.theText.text = “”;
}
[/cc]

Javascript:
[cc lang=”javascript” tab_size=”2″ lines=”40″]
function recieveTextFromFlash(Txt) {
document.getElementById(‘htmlText’).value = Txt;
}
[/cc]

HTML: view Source of sample page

Download:

Download all source files (.fla, .html, .swf): ActionscriptJavascriptCommunication.zip

Integrate Google Analytics with Flash | Tutorial

The results are in and the requested topic is “Integrate Google Analytics into Flash.” The poll has been reset and is ready to recieve your post requests, so keep voting! It’s located in the side bar!

Overview:

Tracking your visitors and attempting to better understand them is a large part of even having content on the web. Since the days of visitor counters displayed proudly on every site, along with dozens of animated gifs to the days when site were designed solely with efficiency and conversion in mind. There are many services that will do this for a fee and other that will do it for free. A popular free web analytics tool is provided by Google. Google Analytics is started by including JavaScript on each page the user wishes to track. This JavaScript loads larger files from the Google webserver and then sets variables with the user’s account number. This JavaScript is used to track and log page views and visitors interaction with the site. This post discusses what to do if your site includes a lot of interactive flash elements you wish to track as well. With the little Google has published related to this(New Code, Old Code), I’ve tried to fill in.
Note: This explains how to set up to track flash events as page views, which does have a drawback- it inflates your pageviews in the analytics and in turn may skew your data. Il’l beposting again soon about how to use then new event tracking, which would track flash events not as pageviews, but as events and thus not inflate the page view count.

UPDATE

I now have an Event Tracking Tutorial as well with actionscript updates!
Event Tracking With Google Analytics & Flash/Actionscript Integration Tutorial

Steps:

  1. If you haven’t already, install Google Analytics on your site. (Note that your analytics tracking code must be placed on the page above the flash call(s) to _trackPageview or urchinTracker)
  2. Determine which events in flash you want to track.
  3. Place in the external.interface code in your actionscript at the specific event(s).
  4. Watch the events get logged in you Google Analytics Reports!

Example:

Here’s a simple example, say you want to track how many times an object is clicked or dragged by a user or how many times it bounces (something that could be tracked but doesn’t necessarily have any required user interaction). In this example flash file I have a ball which bounces off the walls and users can click to drag and even throw it, press the spacebar to create more balls and toggle the gravity on and off with the arrow keys (up is weightlessness, and down is gravity). Each of these events has code to communicate with Google Analytics JavaScript and track the events. I made my own function to call the google analytics code. Do I hear “but sometimes I want to use the new version of Google analytics, and sometimes I want to use the old one…” Have no fear, this function works for either one, or even both. If you’re not using the newer code the calls to the functions in the new code (pageTracker._trackPageview()) will be ignored and vice versa, if you are using the new code, then the calls to the functions in the old code (urchinTracker()) will be ignored, since the functions are not defined. You can track virtually anything with this method. I’ve exaggerated greatly in this example- just to show the variety of different ways this can be used. You might want to make certain the things you track will be useful and relevant for you.

Here is the swf file, I’ve added a text box that will print all actions that are logged to Google Analytics
[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/01/integrategoogleanalytics/integrategoogleanalytics.swf” width=”550″ height=”550″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

track Google Analytics actionscript function
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
function trackGA(action:String) {
//Old Google Analytics Code
ExternalInterface.call(“urchinTracker(‘/urchin/IntegrateGoogleAnalytics/”+action+”‘)”);
//New Google Analytics Code
ExternalInterface.call(“pageTracker._trackPageview(‘/pageTracker/IntegrateGoogleAnalytics/”+action+”‘)”);
trace(“Google Analytics Tracking: ” + action);
}
[/cc]

Calls to Google Analytics actionscript function
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
trackGA(“swfLoaded”);
trackGA(“ball/”+_root.id+”/created/”);
trackGA(“ball/”+this.ballNum+”/released/”);
trackGA(“ball/”+this.ballNum+”/pressed/”);
trackGA(“ball/”+this.ballNum+”/bounced/top”);
trackGA(“ball/”+this.ballNum+”/bounced/left”);
trackGA(“ball/”+this.ballNum+”/bounced/right”);
trackGA(“ball/”+this.ballNum+”/bounced/bottom”);
trackGA(“gravity/on”);
trackGA(“gravity/off”);
[/cc]

Download:

IntegrateGoogleAnalytics.zip

Update:

Here is a screenshot of my Google Analytics Top Content after I search for “pageTracker/IntegrateGoogleAnalytics” (because I’m using the new code version, if I were using the old version I’d search for “urchin/IntegrateGoogleAnalytics”). This just shows that every event was logged to Google Analytics. This screenshot was taken mere hours after this post published.
Google Analytics Screenshot pageTracker/IntegrateGoogleAnalytics/

New Event Tracking technique tutorial rather than posting each event you want to track in flash as a pageview it can be a specific event!

Customize the Right-click menu in Flash | ContextMenuItem Tutorial

Overview:

Flash give publishers the opportunity to customize the right-click menu which pops up in the swf file with a context menu item in actionscript.

ContextMenuItem
ContextMenuItem(caption:String, callbackFunction:Function, [separatorBefore:Boolean], [enabled:Boolean], [visible:Boolean])
Creates a new ContextMenuItem object that can be added to the ContextMenu.customItems array.

Steps:

The menu item has a caption, which is displayed to the user in the right click menu. It also has a a callback function handler by naming the function in the code to be invoked once the menu item is selected. It then has three boolean values which specify whether the item has a separator before it, is enabled, and is visible.

To add a new context menu item to a context menu, you simply create the context menu items and then push them into the customItems array.
You can enable or disable specific menu items, make items visible or invisible, or change the caption or callback handler associated with a menu item at any time.
In the example here the menu items about clearing and rewriting the text are set to toggle each other, so you can’t rewrite the text if it hasn’t yet been cleared and vice versa.

To further customize the context menu flash allows us to hide the built in items in the menu with hideBuiltInItems(). This hides all the built in item from view (except ‘settings’) by setting their visibility to false.

Example:

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/01/right-clickmenu.swf” width=”550″ height=”550″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]
Actionscript:
[cc lang=”actionscript” tab_size=”2″ lines=”60″]
var myMenu:ContextMenu = new ContextMenu();
myMenu.hideBuiltInItems();
var ccs:ContextMenuItem = new ContextMenuItem(“Visit Circle Cube Studio”, visitCCS, false, true, true);
var pog:ContextMenuItem = new ContextMenuItem(“Visit Interactive Flash Portfolio”, visitPOG, false, true, true);
var ct:ContextMenuItem = new ContextMenuItem(“Clear Text”, clearText, true, true, true);
var rw:ContextMenuItem = new ContextMenuItem(“Rewrite Text”, rwText, true, false, true);
var mt:ContextMenuItem = new ContextMenuItem(“Move Text”, moveText, false, true, true);

myMenu.customItems.push(ccs, pog, ct, mt, rw);
_root.menu = myMenu;

function visitCCS () {
getURL(“https://circlecube.com/circlecube”, “_blank”);
}
function visitPOG () {
getURL(“http://www.circlecube.com/test/”, “_blank”);
}
function clearText() {
myText = “”;
ct.enabled = false;
rw.enabled = true;
}
function rwText() {
myText = “Rewrite: \nRight-click to see the customized menu”;
ct.enabled = true;
rw.enabled = false;
}
function moveText() {
theText._y += 10;
}
[/cc]

Download:

Download the Zip file (right-clickMenu.zip)