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
Related
So I am working on a testing application and I need to call a finsihTheTest() function (i.e. this function finishes the test by saving answers, time and other information) whenever following conditions occur:
User tries to reload page.
User tries to go back from the page.
User tries to close the tab.
User tries to close the browser window.
User goes to another url.
If anything happens that closes the page like laptop/PC shutdown, internet lost or anything else.
What I exactly want to do is, if once a user starts the test and by any mean he attempts to leave I want to save his state. Which is being done by the function finishTheTest().
I got a clue but it didn't work:
function UnLoadWindow() {
return 'We strongly recommends NOT closing this window yet.'
}
window.onbeforeunload = UnLoadWindow;
To get the full results for your cases there's many things you should now on how browsers react on many scenarios.
To understand more please read this section :
Especially on mobile, the unload event is not reliably fired. For example, the unload event is not fired at all in the following scenario:
A mobile user visits your page.
The user then switches to a different app.
Later, the user closes the browser from the app manager.
Also, the unload event is not compatible with the back/forward cache (bfcache), because many pages using this event assume that the page will not continue to exist after the event is fired. To combat this, some browsers (such as Firefox) will not place pages in the bfcache if they have unload listeners, and this is bad for performance. Others, such as Chrome, will not fire the unload when a user navigates away.
If you're specifically trying to detect page unload events, it's best to listen for the pagehide event.
window.addEventListener('pagehide', function(event) {
document.cookie = "saveData=test"
},false)
This way you can save your user current data and reload it on next page window load event
I need to be able to detect when a user re-opens their browser after they go to their homescreen by clicking the home button on a mobile phone.
Is there an event I can subscribe to or something?
EDIT: To make this extremely clear, I am looking for a solution based in the web, not a mobile app. I need a js event or something to detect when my website is reopened.
The unload event can be monitored to check if the page has been closed dues to navigation away from the page or specific user action has been take to close the page.
The beforeunload evemt is similar to unload but it may be possible to ask if the user wants to stay on the page. If you want to debug when this event occurs I would suggest saving a message in local storage and logging (or otherwise alerting) it in debug code when the page is loaded again.
The blur event can be used to see if the page has lost focus by checking the relatedTarget property of the event object - if focus has been transferred off page it will be null.
None of these can implicitly check if the user actually went to the home screen and came back, and I would consider it a security breach if you could tell exactly. The blur event can at least tell if the page has lost focus, but will fire in a desktop environment if the user clicks on, say, the address bar.
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.
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.
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...?
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.
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.
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?