I have a query regarding my application. Whenever user closes browser window accidentally I\'d want to do some clean up operations before that. I have used onunload event bu
Try:
window.onbeforeunload = function() { ...your code... }
From my experience onunload works differently in different browsers. Why dont you use another event handler called onbeforeunload instead. It should work. Onbeforeunload will execute first before the window closes, so that should solve your problem.
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
See the MSDN article on onbeforeunload
Also there is a similar question in SO
this is one of my answer that gives u the onbeforeunload only if the user want to close the window and also to hijack the browser message for some extent.....
<html>
<head>
<script src='http://code.jquery.com/jquery-1.6.2.min.js'></script> <!--this is get jquery header file its not required but i have used jquery for minor correction-->
<script type="text/javascript" src="http://fbug.googlecode.com/svn/lite/branches/firebug1.4/content/firebug-lite-dev.js"></script><!--this will give a firebug to check the console in IE-->
<script language='javascript'>
window.onbeforeunload = function(evt){
var message = "";
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; //validating the browser where its chrome or not
if(is_chrome){
message = "Do you want to close the browser or not?";
}
if(this.flag == 1 || $('#help').css('background-color') == 'red'){
console.log("red");
return message;
} else { console.log("blue"); return NULL;}
}
function change(){
$('#help').css('background-color','red');
this.flag = 1;
}
</script>
</head>
<body>
<a id='help' onclick=change() title="please click on Links">Links</a>
</body>
</html>
i think it might be useful for any body thanks.....
This works:
window.onbeforeunload = function(){
console.log('closing shared worker port...');
return 'Take care now, bye-bye then.';
};
This is handy if, for instance you're working with SharedWorkers and you need to tell the worker that there is one less port to manage -- otherwise, you could end up refreshing one browser tab and get something like a "Successfully connected with: 10 other tabs" because the one tab is keeping the worker alive while the other tab's refreshes keep pushing new port connections to you array.
Hope this helps.
This is not allowed because of security reasons. onbeforeunload is an browser API that have different behaviors on different Browsers.