window.onbeforeunload
event is calls before your page is unload
ed.
There is no method to check if it's refresh or browser window close event.
It fires by different scenarios MSDN:
- Close the current window.
- Navigate to another location by entering a new address or selecting a Favorite.
- Click an anchor that refers to another document.
- Invoke the
anchor.click
method.
- Invoke the
document.write
method.
- Invoke the
document.close
method.
- Invoke the
window.close
method.
- Invoke the
window.navigate
or NavigateAndFind method.
- Invoke the
location.replace
method.
- Invoke the
location.reload
method.
- Specify a new value for the
location.href
property.
- Submit a form to the address specified in the ACTION attribute via the INPUT
type=submit
control, or invoke the form.submit
method.
- Invoke the
window.open
method, providing the possible value _self
for the window name.
- Invoke the
document.open
method.
- Click the Back, Forward, Refresh, or Home button.
And you can't handle this.
Also note that window.onbeforeunload
event supposed to inform user that he leaves page and handler function should return
string value that will be included in confirmation popup (except Firefox 4+
see bug).
You can not force the user to stay on the page.
Note: The only thing you can do with onbeforeunload
is to notify the user that he is leaving your page
(this is because some evil pages can open another pages and so on... and spam users. This is security restriction).
If you want to make AJAX call before window is unloaded you need to use onunload
event. Note that your AJAX call must me synchronus. Asynchronous call will not work.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…