2

I need to do remind the users something when they are leaving the page, and that can be handled with the window.onUnload event. But I also need to check if the user is navigating away by submitting the form on the page, or by clicking the navigation links. I could use the form's onSubmit event to set a flag, and then check against that flag in the window.onUnload event, but I am not sure which one fires first.

any ideas ?

disc0dancer
  • 9,185
  • 11
  • 36
  • 46

3 Answers3

5

You actually want window.onbeforeunload

window.onbeforeunload = function (e) {
  var e = e || window.event;

  // For IE and Firefox
  if (e) {
    e.returnValue = 'Are You Sure?';
  }

  // For Safari
  return 'Are You Sure?';
};
Chad Grant
  • 44,326
  • 9
  • 65
  • 80
  • I know it is a little old but [this source](https://developer.mozilla.org/en/DOM/window.onbeforeunload) explains that this functionality is pre-Firefox 4. – arin Apr 24 '12 at 15:06
0
var isRefresh = true;
window.onunload = function () {
    alert('the page was ' + (isRefresh == false ? 'NOT ' : '') + 'refreshed');
}
$('a').live('click', function () { isRefresh = false; alert('a link was clicked'); });
$('form').bind('submit', function () { isRefresh = false; alert('form was submitted'); });

Based on How to capture the browser window close event?. I added the refresh logic.

Community
  • 1
  • 1
Brad
  • 15,361
  • 6
  • 36
  • 57
0

It turns out that the form.onSubmit event fires first so i can use a flag. I have checked this in Firefox and Safari only.

disc0dancer
  • 9,185
  • 11
  • 36
  • 46
  • onsubmit will not fire if they refresh the page, click back, type a new url. To prevent loss of work, stick to onbeforeunload. By the way, for it to work properly, it must be done as Chad Grant described, not by addEventListener – Ruan Mendes Mar 09 '10 at 15:23