DM.
DM.

Reputation: 21

How can I get reason of page unloading in javascript's onunload event, in IE?

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...?

Upvotes: 2

Views: 2883

Answers (3)

seint
seint

Reputation: 11

on unload cant handle its looks like but maybe when load you can handle. as explained performance.getEntriesByType("navigation")[0].type

You can check this Link What is the replacement for performance.navigation.type in angular?

Upvotes: 0

Rajat
Rajat

Reputation: 34128

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.

Upvotes: 0

alex
alex

Reputation: 490303

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.

Upvotes: 1

Related Questions