Trigger Javascript functions from Flash AS3
Thursday, February 4th, 2010Using the ExternalInterface in AS3 it’s never been easier to trigger Javascript functions on your page that holds your swf.
Previously with AS2 and below We would have used the getURL(“javascript:yourFunction();”) or
fscommand(“messagebox”, “Message box called from within Flash.”)
I was asked on the forums today how this would be done in AS3.
After quickly looking up ExternalInterface in the flash Doc’s I was able to through together a quick working example.
A working example can be seen here.
Here is the code:
-
import flash.external.*;
-
import flash.net.*;
-
//Make sure buttons show mouse over
-
but1.buttonMode=true;
-
but2.buttonMode=true;
-
but3.buttonMode=true;
-
//Added mouse event to buttons
-
but1.addEventListener(MouseEvent.MOUSE_DOWN,triggerJavascript,false,0,true);
-
but2.addEventListener(MouseEvent.MOUSE_DOWN,triggerJavascript,false,0,true);
-
but3.addEventListener(MouseEvent.MOUSE_DOWN,triggerJavascript,false,0,true);
-
-
//Function to be triggered by mouse event
-
function triggerJavascript(e:Event) {
-
//check name of button pressed
-
switch (e.target.name) {
-
case "but1" :
-
//open url in fixed size popup
-
ExternalInterface.call("openPopup", "http://www.innovativedesigns.org.uk");
-
break;
-
case "but2" :
-
//open url in new window
-
ExternalInterface.call("openURL", "http://www.innovativedesigns.org.uk");
-
break;
-
case "but3" :
-
//trigger javascript alert box
-
ExternalInterface.call("triggerAlert", "Alert was triggered from Flash");
-
break;
-
}
-
}







