Reputation: 2475
I have written some code, which will ask for confirmation before leaving the page. and if i say Yes to leave the page, then some cleanup needs to be done. Now the problem is onunload
method is getting executed for page refresh
but not for page close
, why?
Code:
function checkBrowser(){
window.onbeforeunload=warning;
window.onunload = unloadPage;
}
function unloadPage() {
if($('#loginOrNot').val() == 'loggedIn'){
setTheExpertStatusToOffline();
cleanUpChat();
}
}
function warning(){
if($('#loginOrNot').val() == 'loggedIn'){
return "You are leaving the page";
}
}
Upvotes: 1
Views: 3267
Reputation: 73
window.onload=function(){
document.getElementById('refresh').onclick=function() {
window.onbeforeunload = null;
window.location.reload(); // replace with your code
}
window.onbeforeunload = function() {
return "Are you sure you want to leave?";
}
}
Upvotes: 4
Reputation: 13379
onunload
event works only when page is being redirected or refreshed. only onbeforeunload
works while closing..
Edit:
Reason in simple terms may be that once browser closes,it doesn't execute the code that was supposed to happen for onunload
event
Upvotes: 2