Avg. Rating 4.0

Problem

In some of application user directly close the browser or tab of that browser, in this case we need to maintain or manipulate or save some data as per the requirement. In flex there is no direct option that detect the browser or tab close event.

Solution

Using JavaScript and Flex's ExternalInterface we can able to detect the close event of the browser or tab. when ever tab or browser close than 'onunload' event of body of that page called, in that method we call the method of swf(Flex object) which already listen the function using ExternalInterface in flex side.So when ever unload event occur it called flex actionscript method as in register in ExternalInterface addCallback method.

Detailed explanation

In Flex side we simple register method name with its function which is called by the javascript, on unload event of body.

//////////////////////////// Flex Application ////////////////////////////////////////

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"

creationComplete="onCreationComplete(event)">
 
<mx:Script>
<![CDATA[
import mx.events.FlexEvent;
 
private function onCreationComplete(event:FlexEvent):void
{
ExternalInterface.addCallback("sendToActionScript", onPageUnload);
   }
 
       private function onPageUnload ():void
       {
           trace ( "Browser Closed" );
}
 
]]>
</mx:Script>
 
</mx:Application>
//////////////////////////// Flex Application ////////////////////////////////////////
 
Add below code in head section of html page
 
//////////////////////////// HTML/JavaScript ////////////////////////////////////////
<script language="JavaScript" type="text/javascript">
 
function thisMovie(movieName) {
         if (navigator.appName.indexOf("Microsoft") != -1) {
             return window[movieName];
         } 
         else if (navigator.appName.indexOf("Netscape") != -1) {
             return document[movieName];
         }
        else {
             return document[movieName];
         }
     }
 
function onUnload() {
        // here Test is the swf embed object name 
         thisMovie("Test").sendToActionScript();
     }
 
</script>
//////////////////////////// HTML/JavaScript ////////////////////////////////////////
 
its helps a lot.
 
Thanks, Virat Patel

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes