Calling ActionScript 3 from Javascript
27.03.2008I really hate Javascript. It’s so inconsistent, loosely typed and annoying to debug. But there are some things that you just can’t do without Javascript. For instance, allowing an HTML page to communicate back and forth with an embedded Flex application.
The Flex documentation gives a very good example of how to call an AS3 method from Javascript. It’s simple, it’s easy to understand and it doesn’t work properly in a real life scenario. But let’s start with the AS3 code example from the documentation:
function callMe(name:String):String
{
return "busy signal";
}
ExternalInterface.addCallback("myFunction", callMe);
And here’s the corresponding Javascript and object/embed tags for use in an HTML page:
<script language="JavaScript">
// result gets the value "busy signal"
var result = flashObject.myFunction("my name");
</script>
...
<object id="flashObject"...>
...
<embed name="flashObject".../>
</object>
All well and good. And it works, too. That is, except when you are dynamically adding object/embed tags with Javascript’s document.write(). Which is what you do, if you don’t want that annoying security frame around your Flex application in the browser. If you use document.write(), the above method only works in Internet Explorer. Not FireFox. Whaaa? I could have sort-of understood it, if it were the other way around.
Anyways. The solution, which I was unable to find in the Flex docs, is the call the flashObject’s method using the following Javascript syntax:
var result = document["flashObject"].myFunction("my name");
Sheez. Only took me an hour to figure out. Hope someone else finds this post if they are in a similar situation.
I really hate Javascript.
Posted by Claus Topholt