Difference between onbeforeunload and onunload

2019-01-06 16:58发布

问题:

What are the differences between onbeforeunload and onunload ? Also I have a specific question related to it's use on the iPad...I have a page (myPage.html) where I am trying to show an alert when the page is closed (i.e. X is pressed to close the tab on iPad)

Now I tried using both window.onunload and window.onbeforeunload Below are my findings on the iPad;

  1. Using window.onunload , I am able to get an alert when user navigates to a different page from myPage.html (either by clicking on some link or doing a Google search while on myPage.html) . However nothing happens when the tab is closed from the minimized view (X)

  2. Using window.onbeforeunload, I neither get an alert even if the user navigates to a different page from myPage.html OR if he closes the tab (X) from the minimized view.

I wanted to know if there is any alternate way to fix this issue ?

Thank you.

回答1:

onunload is responsible for executing an instruction when the page is closed. It also causes issue with IE and AJAX.

onbeforeunload is more efficient because it does not run in competition with the actual closing of the window and is triggered before onunload

I know Opera used to not acknowledge onbeforeunload - not sure if they've fixed that, but I always register the listener for both to be safe:

window.onunload = window.onbeforeunload = (function(){...


回答2:

Adding with AlienWebguy's ans, to avoid dual calls at the browsers that support both events,

var onBeforeUnLoadEvent = false;

window.onunload = window.onbeforeunload= function(){
if(!onBeforeUnLoadEvent){
  onBeforeUnLoadEvent = true;
  //your code here
  }
};


回答3:

onbeforeunload:

  • Called before unloading begins
  • MDN tells me you can cancel the closing of the page using event.preventDefault();
  • or by returning a non-void value (ie a value != 0), the page will pop up a confirmation dialog that allows the user to choose to cancel the close
  • MDN also says Opera 12 and up support onbeforeunload - looks like its supported it for a while now

onunload:

  • Called after unloading has begun, but before any resource deallocation (its not clear to me what exactly is done during this period)
  • Its too late to cancel the page close at this point

The only reason I can think of why you would want to use onunload over onbeforeunload would be where your onunload code could take some significant time, and don't want the user to see a window that hangs while closing.



回答4:

One significant difference (other than cancelability) between the onbeforeunload and onunload is that the former is triggered for download links and the latter is not. Example: <a href="https://somewhere.com/thething.zip">download</a> will trigger the onbeforeunload handler, but not the onunload.