views:

1455

answers:

3

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 ?

A: 

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.

Justin Niessner
external interface i can handle.. how do you check it in javascript ?
Andy Jacobs
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.
R. Bemrose
+2  A: 

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...

Joel Hooks
A: 

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+"};}";

Nick