Hi I want to capture event of windows closing and want to remove session values . After several search I found onBeforeUnload event which is triggered each time when you navigate to different page or unloads the page.even on reload this event will be triggered which is not my requirement. I want specific only windows closing event in all browsers to invalidate the session values.
Run JavaScript code on window close or page refresh?
/* The most acceptable answer seemed to be as follows in vanilla JS
and was addressed at the linked address already.*/
window.onbeforeunload = closingCode;
function closingCode(){
//I would capture the URL prior to unload here and if it does NOT
//exist or is not your url domain then you can unload variables here
return false;
}
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 have an HTML page that includes only a script tag, I don't control the script and I can't change it (so I can't fire my custom event for example).
The script ends with a redirect (using window.location).
Is there a way to add a new script to the page that will listen to the page events and "catch" the redirect (actually it's better for me to catch the new loaded document)?
Something like:
window.addEventListener('redirected', function() {
// do staff
});
(I know there is no "redirected" event, it's just for the example).
It's very important to make it clear that the redirect isn't caused by an anchor click or back/forward button click, so I can't use events like click or popstate.
You might want to look at the onpagehide event or the onunload event, both of which occur when the user navigates away from the page.
However, if you wish to interfere or prevent the redirection itself, onbeforeunload is what you want.
Just take a look at :
unload function w3school or mozilla developper network
beacon function for sending a final XMLHttpRequest
I develope a chrome extension; with a content script I inject some code in the page. What I want is an event that triggers if the current tab is going to update.
I tried to catch the click event of an a-element and it does work in somehow 80% of all cases. I already check if it's an anchor, but there are still many links which don't reload the page or forward to another.
$('a', document).click(function (e) {
// ...
});
So, what I want is described in the following three steps:
Event: the page is going to reload
prevent it from reloading, execute some code
trigger reloading the page afterwards
Depending on your requirements, have you considered listening to beforeunload event? It's fired when the page is about to unload (also including refresh the current page).
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.
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?