Home  >  

Calling JavaScript from Flex

Author photo
| | Comments (7)
AddThis Social Bookmark Button

You might be surprised to know that Flex can create a JavaScript function and call it on the fly. For example, here is a snippet of ActionScript that shows how to obtain the URL of the page that invoked a Flex web application:

import flash.external.ExternalInterface;
var href:String;
if (ExternalInterface.available)     href = ExternalInterface.call("function() { return location.href; }");

The page hosting the Flex application does not need to have any such function defined; the Flex application creates an anonymous function on the fly and calls it, returning the result. Most cool!

No FlashVars were harmed in the writing of this blog posting.

_______________________________

Mike Slinn
Independent full-service software contractor and author
http://slinnbooks.com
http://mslinn.com

Read more from Mike Slinn. Mike Slinn's Atom feed mslinn on Twitter

Comments

7 Comments

teerasej said:

Wow! this is very interesting! So I wonder, is it possible to call Javascript framework from this on the fly coding?

radekg said:

@teerasej: of course it is, inside your function you can place whatever JS string you can think of. You can even load external JS on demand with document.createElement("script");

Utkal R pradhan said:

This is already present in Curl, where you can call JavaScript functions and vice-versa !

bas said:

There are some gotchas involved while executing code this way, especially when your javascript becomes a little more complex then the example above. We have a (commercial) product that takes care of these for you.

Thanks 4 listening!

This works quite well, but not perfectly. For example it seems Internet Explorer doesn't do everything it should with ExternalInterface. I'm still digging at it...

Lars said:

Yes, neat and useful, but I'd say it's a feature of ActionScript and Flash Player rather than Flex, the Flex framework is not required for this.

ariel sommeria, perhaps the problem you encountered in IE is the know problem for the combination of SwfObject, a Flash within a form tag and ExternalInterface calls:

http://www.google.com/search?q=externalinterface+ie+form+swfobject

Leave a comment


Tag Cloud

Question of the Week: Dream App

If you had an unlimited budget and unlimited resources what application would you build and why would you build it?

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.