JavaScript + onbeforeunload

半腔热情 提交于 2019-11-26 17:48:27

问题


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 but problem is this event is sometimes is firing and sometimes doesn't. What should I do, is there better way to handle such type of problem.


回答1:


window.onbeforeunload = function() {
    return 'You have unsaved changes!';
}

See the MSDN article on onbeforeunload

Also there is a similar question in SO




回答2:


Try:

window.onbeforeunload = function() { ...your code... }



回答3:


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.




回答4:


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.




回答5:


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




回答6:


This is not allowed because of security reasons. onbeforeunload is an browser API that have different behaviors on different Browsers.



来源:https://stackoverflow.com/questions/1270395/javascript-onbeforeunload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!