| home / experts / dhtml / diner / beforeunload |
This is an Internet Explorer 4+ for Windows technique.The in-page examples will only work in Explorer 4+ Windows. |
The IE onBeforeUnload Event HandlerCancelling Event HandlingIf you have set the onbeforeunload handler, and later want to cancel the event handling, you simply assign it a null value: window.onbeforeunload = null; An ExampleIn our example scenario, we have an interactive Web page. Let's say the page has a game, of the puzzle variety, that requires solving. This page may be several levels deep in the Web site. That is, the user has navigated to it, with the intention of playing it and solving it. It may be a secure page. The user has already typed in a lot of information, including passwords, to get here. In other words, we are assuming that the user does not want to leave the page UNLESS the game is solved. The user, lazily, while pondering the next move, double-clicks the browser's title bar to maximize the window. The user's aim is off and the double click registers on the top-left icon. The session is over and the user must repeat the navigation from the beginning. The user then:
With a few lines of code, we could have salvaged this user's visit: <SCRIPT LANGUAGE="JavaScript1.2" TYPE="text/javascript">
<!--
isSolved = false;
function unloadMess(){
mess = "Wait! You haven't finished."
if(!isSolved) return mess;
}
function allSolved(){
isSolved = true;
}
//-->
</SCRIPT>
In the above code, the dialog is displayed only when isSolved is false, the default. Somewhere else in our code, when the user solves the game, we call allSolved() which assigns a true value to isSolved, thus avoiding the dialog. Alternately, we can toggle the value of the handler itself: <SCRIPT LANGUAGE="JavaScript1.2" TYPE="text/javascript">
<!--
function unloadMess(){
mess = "Wait! You haven't finished."
return mess;
}
function setBunload(on){
window.onbeforeunload = (on) ? unloadMess : null;
}
setBunload(true);
//-->
</SCRIPT>
In the above example, We can call the setBunload() function with a false argument: setBunload(false); The dialog has been cancelled. Final ThoughtUse this event handler only when necessary, in interactive Web pages and Web applications. In other words, when the user will thank you for it. Don't forget to click OK in the dialog to exit this page! |
Produced by Peter Belesis and
All Rights Reserved. Legal Notices.
Created: Mar 23, 1999
Revised: Mar 23, 1999
URL: http://www.webreference.com/dhtml/diner/beforeunload/bunload4.html