In a previous example, “Calling JavaScript functions from your Flex applications using the ExternalInterface API”, we saw how you could call JavaScript methods from our Flex applications using the static ExternalInterface.call() method.
The following example shows you how you can call ActionScript methods in our Flex applications from JavaScript using the static ExternalInterface.addCallback() method and a bit of JavaScript.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/11/calling-actionscript-functions-from-your-html-templates-using-the-externalinterface-api/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init();">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private var alert:Alert;
private function init():void {
ExternalInterface.addCallback("alert", showAlert);
}
private function showAlert(msg:String):void {
var now:Date = new Date();
alert = Alert.show(msg,now.toLocaleDateString());
alert.status = now.toLocaleTimeString();
}
]]>
</mx:Script>
</mx:Application>
/src/externalInterface.js
/** http://blog.flexexamples.com/2008/03/11/calling-actionscript-functions-from-your-html-templates-using-the-externalinterface-api/ */
function thisMovie(movieName) {
if (navigator.appName.indexOf("Microsoft") != -1) {
return window[movieName];
} else {
return document[movieName];
}
}
function asAlert(value) {
thisMovie("main").alert(value);
}
/html-template/index.template.html
<head> . . . <script language="JavaScript" src="externalInterface.js"></script> </head> <body> . . . <div align=”center”><h1><HTML /></h1></div> <div align=”center”><input type="Button" value="Show Flex Alert" onClick="asAlert(’Hello World, from JavaScript’);" /></div> </body>
View source is enabled in the following example.





When I compiled your example and made my own HTML page it wasn’t working for me, so I figured it must be a difference in how you embed the swf. So I downloaded your exact main.html, externalInterface.js and AC_OETags.js files, and then it worked for me in IE6 but not firefox. So that drove me batty for a while. But I finally figured out that it was because I was running it from my desktop. Running it from my apache server it works in both. Thanks for your help! I appreciate it a lot, and just in case anyone else runs into the same problems, it looks like you have to be running from a server to get it to work consistently.
i’m using it to save a base64 encoded image. i’m wondering, can you load a base64 image in flex?
i found the answer to loading a base64 image: http://code.google.com/p/flexlib/