FLEX 3 Catch Browser Exit or Close Event using Javascript and ExternalInterface
Well after doing a bunch of searching and hacking away, I have managed to come up with a solution!
What I wanted was to set a variable when a change was made in my Flex application. (In my case it meant that a new module was loaded to my dashboard application) This way if a user loaded or deleted a module, the app would save their environment to a Shared Object.
Originally I had it was saving automatically, but user feedback said, only if I want to. This led me to prompting them when the close, but only if something has changed.
Here is how I did it:
First I declare a Bindable variable up at the top of my code (oh also import ExternalInterface)
import flash.external.ExternalInterface; [Bindable] private var saveRequired:Boolean;
Second in my creationcomplete Event called init(), I add a callback to the ExternalInterface like so:
private function init():void
{
if ( ExternalInterface.available ) {
ExternalInterface.addCallback("checkForUnsavedData",function():String {
if (saveRequired ) {
unsavedAlert();
return UNSAVED_DATA_WARNING;
}
else return "";
});
}
}
The following 2 functions are added to handle the Alert when the Javascript kicks off
private function unsavedAlert():void {
Alert.show("Save?", "Save Alert", Alert.YES|Alert.NO ,this,SaveAlertHandler,null,Alert.YES);
}
private function SaveAlertHandler(e:CloseEvent):void {
if (e.detail == Alert.YES) {
setLSO();
}
saveRequired = new Boolean;
}
When you determine that a save is required set the variable saveRequired to anything. I wanted it to be a reminder when I went back to debug, so mine look like this…
saveRequired = "Popup on Browser Exit";
Finally….add this code between
in your ./html-template/index.template.html
<script language="JavaScript" type="text/javascript">
<!--
//alert(navigator.appName);
// Give user a chance to save modified data
window.onbeforeunload = function () {
var warning = getFlexApp('SharedObjectBoard').checkForUnsavedData();
if (warning != "")
return warning;
else
return;
}
function getFlexApp(appName) {
if (navigator.appName.indexOf ("Microsoft") !=-1) {
return window[appName];
alert(appName);
}
else {
return document[appName];
}
}
-->
</script>



























