Wednesday, 17 September 2008

Confirm Browser Window Close with Javascript onBeforeUnload

If you have a web page that if closed prematurly could lose users work or data, then you may want to add a prompt to confirm the user wishes to close window. Rather than the default browser behaviour of just closing or opening a new page over your page in the same window..

To to this you can add an onbeforeunload Javascript function. Please note that this doesn't work with some older browsers.

This is a basic example that should display a message when the window or tab is closed.


<script type="text/javascript">

window.onbeforeunload = function() {
return "Are you sure you wish to close this page?";


<h1>On Before Unload Test</h1>

This should help prevent any lost work.


1 comment:

Razor said...

Thank you so much ...made it so simple :D