Inject custom message to warn user from closing browser window

Written by stevey on June 26th, 2012

In a recent project, I needed to inject a custom message to warn user not to simply close a browser window; they might be doing some online course work and have not sent their course data back to server, and accidentally close down the browser. We didn’t want that to happen. At the beginning, I attempted the window.unload() event, and placed custom message there; but that, strangely, only works in IE7, but not in IE8,9, or recent versions of Chrome.

Naturally, I resolved to jQuery and found that this posting here at http://www.mkyong.com/jquery/how-to-stop-a-page-from-exit-or-unload-with-jquery/ was most useful. The author of this posting gave a good example and even embedded a demo. The thing I wanted to stress is that you must place the javascript code that handles the “beforeunload” event inside the body tag. At first, I placed in in <head> section and the event handler did not fire.

For jQuary library, I used direct reference from Google hosted solution, instead of referencing to local resource. Click hereto see what it looks like with different browsers and view the source. Try to enter a custom message to the text box on the lower part of the page, then try to close your browser. You will see the message you type in the box get added to the browser’s warning message while you try to close the page. For FireFox, it behaves quite differently – the custom message never got displayed and the default message differs from IE and Chorme, as shown in the image.

 

Leave a Comment