2

Possible Duplicate:
how to check users leave a page

For example when somebody refreshes, enters a new URL into the location bar, or navigates away using a link on the page?

I need to do some work after someone attempts to leave my page.

EDIT: onunload doesn't work because in most browsers that doesn't execute until the page they are attempting to leave to returns a response. I want to execute some code as soon as they attempt to leave.

beforeunload appears to work, but I'm not sure a beforeunload without a return is proper form.

Community
  • 1
  • 1
Keith Carter
  • 422
  • 1
  • 6
  • 18

2 Answers2

3

You can use window.onunload which will be executed when the window is unloaded, which also includes navigating to a different page.

window.onunload=function () {  };

I am not sure about what you are trying to do, but check

window.onbeforeunload @ MDN and http://msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspx

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

  // For IE and Firefox prior to version 4
  if (e) {
    e.returnValue = 'Any string';
  }

  // For Safari
  return 'Any string';
};

FYI. Comment out the return if you don't want user to see the Leave Page/Stay on Page prompt.

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • I want code to execute as soon as they attempt to leave the page, not once the page they are trying to leave to returns a response. – Keith Carter Feb 10 '12 at 22:37
  • Didn't realize beforeunload could be used without a return. Interesting. How cross browser is that event? – Keith Carter Feb 11 '12 at 18:37
2

window.onunload, here's docs from MDN, this is the event raised when the document is unloaded.

Mike K.
  • 3,751
  • 28
  • 41
  • I want code to execute as soon as they attempt to leave the page, not once the page they are trying to leave to returns a response. – Keith Carter Feb 10 '12 at 22:43