Wednesday, December 05, 2007

JS: Are you sure you want to navigate away from this page?

I've been using blogger for a while, and not because I don't know how to build my own blog or website. I've build dozens of them, but I use blogger because its easy, and I don't have to worry about the details of the code. Heck I could build a site like blogger if I wanted, it would just take time. Occasionally on blogger I bump into a feature that I don't know how to replicate, and this is one of them.

I've always wondered how blogger uses javascript to ask "Are you sure you want to navigate away from this page? You have unsaved changes."

I was browsing around in some MSDN DOM documentation and found a window event called onbeforeunload. I've actually explored this issue once before and only got as far as onunload. Having the right keyword to put into google makes a real difference.

Add this javascript code to a page and then try to close the page.
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "Are you sure you want to leave this page?";
}


source(s): http://msdn2.microsoft.com/en-us/library/ms536907.aspx, http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm

No comments: