Yogesh's Blog

Sharing me with blog…
Posts Tagged ‘onbeforeunload’

June 30th, 2010

Prevent browser closing

1 Comment, 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…