AS3 Javascript Communication

October 29, 2008 by jared 

I was searching high and low for a solid example of how Javascript and AS3 talk to each other, and couldn’t really find one, so here it is.


See the example here.

Actionscript 3 to Javascript

In this example we’ll use Javascript to create a popup window from Flash.

If you click on the “Pop up!” button, the following code from JavascriptPopup.fla is executed inside the click button event handler.

var jscommand:String = "window.open
('http://jared.simplistika.com','win','height=170,width=350,
toolbar=no,scrollbars=yes');";
var url:URLRequest = new URLRequest("javascript:" + jscommand + " void(0);");
navigateToURL(url, "_self");

Only thing is if you do a CTRL + Enter locally on your computer, nothing will work. To test it you’ll have to upload it to a server which I’ve done here. Pretty easy to just replace your own Javascript from here on.

Javascript to Actionscript 3

Still inside JavascriptPopup.fla, we have

ExternalInterface.addCallback("changeText", changeTheText);

which basically sets up Flash to communicate with the HTML page. Two things to note:

changeText refers to the Javascript function we will be calling from the HTML. Give this any name you want but remember it because we’ll be using it later.

changeTheText refers to the Actionscript function which is exactly right below that line of code.

function changeTheText(t:String):void {
	txtText.text = t;
}

And what this function does is simply set up the textbox in our Flash project named txtText to a String value which will be sent via Javascript later on.

And so to set up the link in our HTML page, we use this line

<p><a href=”#” onClick=”JavascriptPopup.changeText(‘it works!’);”>Click me!</a></p>

Where JavascriptPopup refers to the id (look for an id attribute in the generated HTML file) of your flash movie, in this case it is JavascriptPopup, changeText is our function defined earlier, and ‘it works!’ is our text that we are sending into Flash.

Click here to download files in this example.

AS3 XML Thumbnail Photo Gallery

October 26, 2008 by jared 

Just a basic example of a thumbnail XML driven photo gallery. This version limits the number of thumbnails to the width of the photo, it’s not a perfect solution but at least it’ll get you started somewhere!

Download here.

AS3 XML MP3 Player Pro

October 22, 2008 by jared 

Only $5.00!

Click here for more details.