Yogesh's Blog

Sharing me with blog…

June 30th, 2010

Prevent browser closing

Javascript, by Yogesh.

Due to some reason,  sometime we want to prevent closing of browser. Actually for security reason, we can not force client to keep browser window open, but what we can do: we can ask client confirmation for it.

So to prevent closing of browser window, following javascript code can be used. This works in IE, Mozilla, Safari (Checked with IE6, IE7, IE8, Mozilla firefox 3.5, Safari 5)
<SCRIPT LANGUAGE="JavaScript">
window.onbeforeunload = function(e) {
e = e || window.event;
var message = "Your message here";
e.returnValue = message;
return message;
};
</SCRIPT>

Here e.returnValue = message; does not work in safari but return message; does.

When the alert will come?

  • – On closing browser using cross button (X)
  • – On refreshing browser (browser’s refresh button or F5)
  • – On hitting address bar (either address is changed or not)
  • – Going back (By hiting back button or Backspace)
  • – By clicking link

When alert will not come?

  • – By clicking on link to open pop-up window

Now here comes the condition that you don’t want to show alert when user clicks on particular link to open some other page in same window. Do by this:
<SCRIPT LANGUAGE="JavaScript">
var showPreventMessage = true;
window.onbeforeunload = function(e) {
e = e || window.event;
if(showPreventMessage){
var message = "Your message here.";
e.returnValue = message;
return message;
} else {
// it means here you don't want to show message.
}
};
function disablePreventMessage(){
showPreventMessage = false;
}
</SCRIPT>

Now just call the disablePreventMessage function on the onClick event of link you don’t wan’t to show prevent message and want that user should easily navigate to page.
<a href="www.google.com" >GOOGLE</a><br/>
<a href="www.google.com" onclick="disablePreventMessage();">Let me navigate without alert</a></br>
<a href="www.yahoo.com" target="_blank">YAHOO POPUP</a>

Here on clicking “GOOGLE” link, prevent message will appear and ask you for confirmation.

On clicking “Let me navigate….” link, you can smoothly navigate without any confirmation.

On clicking “YAHOO POPUP” link, no alert will be shown and popup window will be opened.

Here is also a limitation that you can not change the default behavior of this alert box and default text on box. You can just only add your own text which will come as center text of default text. Try it, you will get better idea.

Back Top

Responses to “Prevent browser closing”

Leave a Reply

Your email address will not be published. Required fields are marked *