Difference between onbeforeunload and onunload - javascript

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;
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)
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.

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(){...

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

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.

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: download will trigger the onbeforeunload handler, but not the onunload.

Related

Fire onbeforeunload only when window is closed (includes working example)

I want to fire the onbeforeunload event only when the tab or browser is closed and not upon refresh, link click and so on. I found a site where that works: https://checkout.deindeal.ch/
Steps to fire the event in Chrome:
Put something into the cart
Click on "Zur Kasse"
Close tab
onbeforeunload Message is shown and a popup opens. onbeforeunload events like refresh will not fire. I debugged their code, but could not find the place where they exclude those events or whatsoever.
Anyone out there who can find the correct place in the code?
Thanks!
For readers that want to use onbeforeunload,
The event onbeforeunload should be used for preventing user's data loss, like filled in forms and other data that are not saved and will be lost upon page refresh.
Using onbeforeunload to prevent a user from leaving your page is annoying and will not stop the user from leaving.
You can not detect a browser tab refresh button press, unless the user use a shortcut that you can detect with key press (like Ctrl+F5).
More info here :
javascript beforeunload detect refresh versus close
Old answer was removed in order not to mislead anyone (it was not working on nowadays browsers).
More stack overflow links related on onbeforeunload use:
How can i get the destination url in javascript onbeforeunload event?
How to prevent calling onbeforeunload when page refresh
Fire onbeforeunload confirm alert for external sites only

Disallow JavaScript from closing window in IE

I'm trying to debug an issue where the browser disappears after refreshing a particular page. I want to see if I can eliminate JavaScript as being the cause of this issue.
Does IE have an equivalent to the Firefox configuration option dom.allow_scripts_to_close_windows?
I did some googling and this was the closest thing I could find, but I do not know if it also prevents JavaScript from closing windows.
Prevent Users from Closing the Browser or Explorer Windows
Edit: You can use the onbeforeunload event to see if the page is triggering some sort of close event.
window.onbeforeunload = function() {
return "The browser is about to close this window, are you sure?"; // Will appear as a confirmation box
};

How to handle browser close (cross) in javascript or Jquery

I need to handle browser close (through cross on the top right side) through javascript or Jquery. I have found lots of forums or blog where they give a solution to do this using onUnload or OnbeforeUnload etc. But these event always get triggered whenever page refresh or go back and forward in browser.
I need to expire cookies only when user signout from application or user close the window. If i use the onUnload or OnbeforeUnload event they get triggered even when page refreshed or back or forward as i have already told.
Any help really appreciated.
Thanks
Non persistent cookies is one workaround. second, you can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
/* Do you small action code here */
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload
OnbeforeUnload can be used for this purpose with some work around. I think you can use a flag value something like wasClose=true/false , which should be made to false when user is clicking on any elements(can be applied for a div/body if it can receive the bubble). The better you can get some js library from web and use.
Else, we will need to manually monitor right clicks, click targets(if inside body) etc.. and decide, the window.close() or a click on close is the event caused the Onbeforeunload() call.

What user actions trigger beforeunload in which browsers?

closing window
refreshing page
clicking on a link
??
It seems to be inconsistent. (I'm shocked!) Is there a list somewhere? I'm particularly interested in Firefox, but am curious about others, as well. The Mozilla docs are vague:
window.onbeforeunload
An event that fires before the unload event when the page is unloaded.
window.onunload
The unload event is raised when the document is unloaded.
Gee, thanks.
window.onbeforeunload will trigger before you navigate to away from current page (from URL address, BACK button, close browser, etc.)
The event will not fire in Opera. But all the other browsers seem to respect it OK.
I have used this in the past for AJAX-intensive sites, mostly as a way to avoid having to support the BACK button.
It also works well as a confirmation dialog to prevent you from accidentally losing your work. But users might get annoyed by the confirmation. So this might not be a good enough reason to use it.

Open new window after a click event not working in Safari, Chrome

I'm trying to open a new window like so:
$('#wrapper').click(function() {
window.setTimeout(function() {
//alert('hi');
window.open("http://example.com", "ExternalLinks", "resizable=yes, scrollbars=yes, status=yes");
}, 1000);
});
This works in Firefox, but not in Chrome or Safari (so far, I've just tested on a Mac). The alert() works in all browsers, so there seems to be something preventing the window.open from executing in Safari/Chrome. Furthermore, if I remove the setTimeout and just call the window.open then it does work in all 3 browsers. It's almost like if the window.open is nested too far away from the click event, then it doesn't work in Safari/Chrome.
So you know, I have an all-Flash website and I'm trying to get external links to open in a new window, so I'm reading the hash tag in the URL (ex. htp://example.com/#/facebook/) and if it matches certain items, then I'm calling window.open to open a specific URL. I don't have access to the Flash source, or I would handle this there.
Any ideas?
Safari/Chrome have built-in pop-up blockers that stop this from working. The only javascript that is allowed to open a new window in Safari/Chrome is javascript directly attached to click handlers (and other direct user input handlers). In past versions people figured out some ways to cheat (like generating some other element -- a form or div -- and simulating user input with javascript), but newer versions are smarter about detecting this. I'd recommend re-configuring things so that you don't use a delayed pop-up -- that is the kind of thing that can generally be jarring to a user after all.
I got around this by checking the return value of window.open() for undefined. If that is true call alert() with a message for the user to to disable their popup blocker.
var myWin = window.open([args]);
if (myWin == undefined)
alert('Please disable your popup blocker');
Another workaround
Just open a popup with ACCEPT and CANCEL options and attach the window.open action to the ACCEPT button and it will works. It worked for me...

Categories