Scenario: you make a nice HTML form for some purpose. A user comes along and spends some time filling it in… and then clicks a link on the page and loses everything they wrote. User never comes back to your site.

What you need is a little bit of Javascript to check for unsaved changes and warn the user before they leave the page if they are going to lose their work. Gutuma uses something like the following:

var is_post_back = false;
 
window.onbeforeunload = function (ev)
{
  var html = document.send_form.msg_html.value;
  var subject = document.send_form.msg_subject.value;
 
  if (!is_post_back && (html != "" || subject != ""))
    return "Your message will be lost if you leave this page.";
}
 
function cancel_unsaved_warning()
{
  is_post_back = true;
}

The cancel function is called in the onclick events of any buttons on the page which do a POST back to the page, and thus won’t lose the user’s work. This is the best way I think to cancel the warning message as setting window.onbeforeunload = null doesn’t work in IE6, and returning anything from the onbeforeunload handler results in a warning message (even null or false), so you have to use some logic to avoid a return statement altogether. Weird but it works.

UPDATE 11/09/08: I’ve just discovered that IE treats javascript: hrefs as navigations away from the page and fires the onbeforeunload event. So you can’t call a javscript function like

<a href="javascript:myfunc()">Link</a>

without seeing the above warning message about leaving the page. But you can get around this by using the onclick attribute:

<a onclick="javascript:myfunc()" href="#">Link</a>

Leave a Reply