Technology

JavaScript: Wait! Are you really sure you want to leave?

StopHave you ever gotten all the way to a submission page only to mess up and close the browser window? I have! I’ve actually gone through an entire purchasing system and added tons of items only to accidentally close the browser. Since most browsers support tabs now, it’s quite easy to do.

Applications that have a multi-step process, review and checkout would be wise to utilize a confirmation prior to the window closing… but it’s not as easy as you think. JavaScript has an onbeforeunload event where you can confirm whether or not the user really wants to leave the page. Here’s an example and here’s the code:

For more information on the onBeforeUnload event, visit the DHTML Lab. You can also pass a false to the script if someone clicks a submission button where you want to leave the page gracefully without the message:

window.onbeforeunload = null;