I've recently been looking for a way to invoke an ActionScript/Flex function based on a browser event… say window.unload (orsomethinglikethat). The ability to hook into Application creationComplete is present, however I am unaware of any built-in Flex/FlashPlayer unload/shutdown hook points.
I’ll now turn my attention to letting the browser notify the Flex Application of events. There are a couple of ways to accomplish this, both of which involve using the flash.external.ExternalInterface.addCallBack() to expose a Flex function to the containing browser:
- Embed or import JavaScript in the Flex application’s HTML wrapper to hard code the browser event handlers to invoke the exposed Flex callback functions.
- Assign the browser event handlers in the Flex code.
Both options have a time and place, but for my purposes, I’ll choose the latter option. I prefer not to maintain additional JavaScript and/or custom HTML wrapper code, and ideally I’d like to be able to directly map a browser event to a Flex function.
Source and Usage
Steps #1 & 3 are uninteresting and strictly interact with ExternalInterface.
Step #2 is a bit more interesting as it involves constructing the JavaScript statement that binds the browser event to the callBackAlias.
Since ExternalInterface.call() uses the functionName parameter as a pointer to a function that has been defined in the tag, it is not possible to pass in a String of JavaScript as we would with the JavaScript eval() function. Instead we “wrap” our JavaScript in an anonymous function to be executed upon ExternalInterface.call() invocation. The script we have just “wrapped” assigns the browser event handler to another anonymous function that contains the script to invoke the provided Flex callBack function by the provided alias. This code could be easily be modified to provide behavior similar to the JavaScript eval() function, but should probably be used with care as (IMHO) embedding JavaScript (even as described in this solution) in ActionScript reduces reliability and maintainability. Besides who wants to worry about cross-browser compatibility of JavaScript embedded in a cross (FlashPlayer) platform Rich Client?
Please let me know of any different/better ways to accomplish this, or if this code has any errors I have not yet found.