views:

313

answers:

2

There may be different reasons of page unloading:
1 User closes the current window.
2 User navigates to another location.
3 Clicks the Back, Forward, Refresh, or Home button.
4 User submits a form, and then browser starts to unload current page and load page with results of form submitting. (Assuming that the current window is the form's target).
5 and so on...

Can I somehow know in onunload handler that the reason of unloading is p.4, i.e. moving to page with results of form submitting?
I could define some flag when submiting form, but this does not solve the problem. Because response (on form submit) from web server takes some time, browser doesn't unload the current page immediately and waits response from server. And during this waiting user may close window or navigate anywhere. And I need to know whether was it indeed moving to results page or something else...?

+1  A: 

You could hijack some of those events.

For example for links, you could add an event handler on links that saves their href attribute, performs what you require, then sets window.location to the href you had stored in a variable.

alex
Thanks, but I need to catch all cases... or one case - moving to submit's results page. Currently I use frames (i.e. onunload event is on the main window and a form is in frame inside main window), but this approach also has drawbacks.
DM
A: 

The exact reason of page unload cannot be known in the unload handler. OnUnload event is not a standard and was implemented by IE first.

Different browsers might handle it differently and fire the event for different cases.

msdn reference

mozilla reference

So if you are trying to know the reason of unload in the unload handler, I think you might be out of luck. However as Alex pointed out in his answer, you could probably know about user navigating away from your page by clicking some link on your page by making your click handlers for those links more intelligent.

Rajat