This weekend my good friend Peter Panton asked my for some help setting up some communication between Javascript and Actionscript. He wanted to be able to get the scroll value of the HTML page and use it in Flash. To be honest, I never did any kind of communication between the two and had no idea where to start. I did some research and came across the ExternalInterface Class.
It took me a while to get how exactly the class worked, but once I got a handle on it, setting up the relation was easy. At first I set up a small test just to see if I can pass information back and forth. Basically is just passes string from the HTML page to Flash and vice versa. You can check it out at ExternalInterface Test 1. All the code will be at the bottom.
Once I jumped for joy with the first example, I got the scroll example to work here. The Javascript just sends the value of the scrollTop to the Flash text field. Since I'm on the Mac, Im not too sure if this works in IE, but it works just fine in FireFox and Safari. The example isn't rocket science but I figure I'd share it anyway. I'll even share the example files for you to play with.
Have Fun
Example 1 AS
import flash.external.ExternalInterface;
sendBut.addEventListener(MouseEvent.CLICK, toJS);
if(ExternalInterface.available)
{
try
{
ExternalInterface.addCallback("sendToFlash", fromJS);
}
catch(e:Error)
{
}
}
function fromJS($value:String):void
{
oText.text = $value;
}
function toJS(e:MouseEvent):void
{
if(ExternalInterface.available)
{
ExternalInterface.call("sendToJS", iText.text);
}
}
Example 2 AS
import flash.external.ExternalInterface;
if(ExternalInterface.available)
{
try
{
ExternalInterface.addCallback("sendToFlash", fromJS);
}
catch(e:Error)
{
}
}
function fromJS($value:String):void
{
oText.text = $value;
}
No comments:
Post a Comment