JavaScript + onbeforeunload

馋奶兔 提交于 2019-11-27 09:01:37
rahul
window.onbeforeunload = function() {
    return 'You have unsaved changes!';
}

See the MSDN article on onbeforeunload

Also there is a similar question in SO

Davide Ungari

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.

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 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 is not allowed because of security reasons. onbeforeunload is an browser API that have different behaviors on different Browsers.

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