I have to detect in my flash if the user closes his browser or goes to another page and the flash is not accessible anymore. How do i achieve that ?
3 Answers
ExternalInterfaceUtil.addExternalEventListener("window.onunload", handleLogout, "unloadFlex");
package
{
import flash.external.ExternalInterface;
public class ExternalInterfaceUtil
{
public static function addExternalEventListener( qualifiedEventName:String, callback:Function,callBackAlias:String ):void
{
// 1. Expose the callback function via the callBackAlias
ExternalInterface.addCallback( callBackAlias, callback );
// 2. Build javascript to execute
var jsExecuteCallBack:String = "document.getElementsByName('"+ExternalInterface.objectID+"')[0]."+callBackAlias+"()";
var jsBindEvent:String = "function(){"+qualifiedEventName+"= function(){"+jsExecuteCallBack+"};}";
// 3. Execute the composed javascript to perform the binding of the external event to the specified callBack function
ExternalInterface.call( jsBindEvent );
}
}
}
I don't remember where I got this from, but I've used it and it works pretty well. Of course not all browsers are going to cooperate, but it is better than nothing...

- 6,465
- 4
- 33
- 39
-
That works fantastically well. Any idea on how listen to the "user clicked on OK button in the JS popup" from inside a flex program? – fred august Mar 07 '11 at 21:48
You could use a combination of Javascript and Flash to achieve what you're looking for.
Use Javascript to detect when the user navigates away from the page. Use the javascript event to call into your Flash movie using ExternalInterface. Once your code is called, you can handle the event as needed.

- 242,243
- 40
- 408
- 536
-
external interface i can handle.. how do you check it in javascript ? – Andy Jacobs Jul 13 '09 at 14:09
-
Javascript has a window.onunload event that you can attach a function to. Unfortunately, some browsers will not always call the onunload event when the user closes the window due to abuse of it in the past. I know for a fact Opera doesn't, I'm not sure about the others. – Powerlord Jul 13 '09 at 14:15
The above worked great for me with one exception: if I return null as my string, I don't want any message to pop up. It works for all browsers except IE, which brings up a dialog box that says "null".
That can be corrected by altering one line to add a null check:
var jsBindEvent:String = "function(){"+qualifiedEventName+"= function(){if (" + jsExecuteCallBack + ") return "+jsExecuteCallBack+"};}";