Difference between onbeforeunload and onunload

testndtv picture testndtv · Aug 1, 2011 · Viewed 35.3k times · Source

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.

Answer

noboundaries picture noboundaries · Nov 13, 2013

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
  }
};