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)

Get current url to Flash swf using an External Interface call

Update: please see the newer tut talking about getting the current url with as3

Overview:

Many have struggled with the task of getting you swf to read or get the current url showing in the browser, the html page the browser is at which has the swf embedded. Not to be confused with the _root._url which returns the path of the swf file. This would be helpful to know if someone is embedding your swfs on their site, or even customize your swf depending on which page it resides on. There is a pretty simple, yet virtually undocumented way to do this. We have to use javascript by calling External Interface and get the url from the DOM. Window.location.href. Then we must call the toString() function only because ExternalInterface.call requires a function rather than only reading a static property.

Steps:

  1. Import external interface into your file: import flash.external.ExternalInterface;

  2. Initialize a variable to store the url path: var urlPath;

  3. Create a function to call external interface and assign the html page path to your variable: urlPath = ExternalInterface.call(“window.location.href.toString”);

  4. Call the function when/if needed.

Example:

With javascript: window.location.href or window.location.href.toString();
With actionscript: ExternalInterface.call(“window.location.href.toString”);
External Interface html Example
[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2008/01/externalinterface.swf” width=”550″ height=”200″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]
Actionscript:
[cc lang=”actionscript” tab_size=”2″ lines=”40″]
import flash.external.*;
var urlPath;

function geturlhttp() {
urlPath = ExternalInterface.call(“window.location.href.toString”);
}
geturlhttp();
//Here I assign the url to a text box on the stage
_root.urlText.text = urlPath;

[/cc]

Download:

ExternalInterface.zip

StomperNet Scrutinizer

StomperNet releases Scrutinizer, software for viewing websites through a simulated fovea vision. Since not everyone could set-up, let alone afford a real eye-tracker. This software uses the mouse pointer as the user’s focal point, or foveal view. It blurs everything except where your focal point (the mouse) is. It is helpful because it forces you to re-think web design from an extreme usability standpoint. This browser software was built in conjunction with Nitobi using Adobe AIR and Flex. I had the chance to do the skinning of the browser in flex! I really hope to have a good excuse to play more with flex.

Scrutinizer Thumbnail

Anyways, check out the free software (master-minded by Andy Edmonds), this ‘Click Fu’ video created to explain it, and the many uses of Scrutinizer.

[kml_flashembed movie=”http://www.stompernet.net/squambido/pagetest/squambido.swf” height=”338″ width=”450″ fvars=” playlistURL = http://www.stompernet.net/GoingNatural20/files/GoingNatural20Public.dhtml.xml ; autoplay = false ; awiz = 1126 ; playlistoffset = 4″ allowfullscreen=”true” fversion=”9″ useexpressinstall=”true” allowscriptaccess=”always” /]

PHP Menu Include function to reuse an html block on multiple pages

Overview:
When making websites frequently we want a navigation bar or menu to show on every page. Rather than repeating the code on every single page, which is virtually impossible to update and maintain, or worse, using frames, use PHP to automate this and build each page dynamically. PHP will just paste in the navigation or whatever you’d want represented on every page. To do this we use the php include function. You can use include() to show headers, footers, or any elements that you’d reuse on multiple pages. The include() function takes all the text in a specified file and copies it into the file that calls the include function. This is great for scalability and updating- instead of changing multiple files, only change one!
Here’s what a php include function looks like:
<?php include(“nav.php”); ?>

Steps:
1. Make the actual nav you want.

2. Put it into a php file (or any type of file, html, txt, as long as it’s formatted as html)

3. Place the php in your page to ‘print’ the desired file into your final html page before the browser renders the page using the include function. This spits out html. The viewer’s only see html, as that’s all it is, the php created the html file- That’s why it’s called PHP: Hypertext Preprocessor.

Example:
The nav.php file:
[cc lang=”php” tab_size=”2″ lines=”40″]

Home |
About Us |
Portfolio |
Contact Us

[/cc]

The homepage.php:
[cc lang=”php” tab_size=”2″ lines=”40″]
<?php include(“nav.php”); ?>

Welcome to my home page

home page text lorem ipsum
[/cc]

And here’s a sample site with a nav bar containing 4 pages included through php for Home, About, Portfolio and Contact.

Download

phpNav.zip

Dynamic Flash Vertical Scrolling Link List with XML

As seen at activeden. I’ve fixed it up a lot and made it much easier to incorporate into your own files.

A link list. Vertically scrolling list of links or just words. Scrolls and wraps automatically and interactively. Reads an external XML file containing just titles and paths and creates an interactive click-able link list!

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2007/08/linklist.swf” width=”550″ height=”500″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

Download the source files (linkList.fla, cats.xml, linkList.swf): Link List at activeden.

Other Circlecube Items at activeden

21075 24687 45713 45893 22018

Dynamic Scrolling Buttons

[kml_flashembed publishmethod=”dynamic” fversion=”9.0.0″ movie=”https://circlecube.com/circlecube/wp-content/uploads/sites/10/2007/04/dynamicscrollingbuttons.swf” width=”550″ height=”400″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]
Here’s an example. A dynamic scroll, that changes speed according to your mouse. Here is the code for it as well, I tried to keep it pretty generic, just put this onto a movie clip I named “scroll.” And change the variables to fit your needs. Enjoy, and let me know what you make with it.

Actionscript (as2)

[cc lang=”actionscript” tab_size=”2″ lines=”40″]

onClipEvent(load) {
//variables
scrollMovieClipW = this._width – Stage.width;
leftScrollMargin = 175;
rightScrollMargin = 275;
verticalScrollMargin = 250;
//Note: The lower acceleration value the faster the scroll will be.
acceleration = 3;
}

onClipEvent (enterFrame) {
//to move left
//if mouse is right of 0 (left edge)
if (_root._xmouse >= 0 &&
//if mouse is left of left scroll margin
_root._xmouse <= leftScrollMargin && //if mouse is vertically below green line (over the scroll movie clip) _root._ymouse >= verticalScrollMargin &&
//if the scroll movie clip can still scroll further
_root.scroll._x <= 0) { this._x -= (_root._xmouse - leftScrollMargin) / acceleration; }//to move right else if (_root._xmouse >= rightScrollMargin &&
_root._xmouse <= Stage.width && _root._ymouse >= verticalScrollMargin &&
_root.scroll._x >= -scrollMovieClipW) {
//move right
this._x -= (_root._xmouse – rightScrollMargin) / acceleration;
}
}
[/cc]

Source

Download the example file: dynamicScrollingButtons.fla