申請に関して質問があります。ユーザーが誤ってブラウザー ウィンドウを閉じるたびに、その前にいくつかのクリーンアップ操作を実行したいと思います。onunload イベントを使用しましたが、問題は、このイベントが発生する場合と発生しない場合があることです。どうすればいいですか、このような問題を処理するためのより良い方法はありますか。
6 に答える
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
onbeforeunload に関する MSDN の記事を参照してください。
SOにも同様の質問があります
試す:
window.onbeforeunload = function() { ...your code... }
私の経験から、 onunload はブラウザによって動作が異なります。代わりに onbeforeunload という別のイベント ハンドラを使用しないでください。それはうまくいくはずです。Onbeforeunload は、ウィンドウが閉じる前に最初に実行されるため、問題は解決するはずです。
これは機能します:
window.onbeforeunload = function(){
console.log('closing shared worker port...');
return 'Take care now, bye-bye then.';
};
これは、たとえば、SharedWorkers を使用していて、管理するポートが 1 つ少ないことをワーカーに通知する必要がある場合に便利です。そうしないと、ブラウザのタブを 1 つ更新して、「接続に成功しました: 10 個の他のタブ」が表示されます。これは、1 つのタブがワーカーを有効に保ち、他のタブの更新が新しいポート接続をアレイにプッシュし続けるためです。
お役に立てれば。
これは、セキュリティ上の理由から許可されていません。onbeforeunload は、ブラウザーごとに異なる動作をするブラウザー API です。
これは、ユーザーがウィンドウを閉じ、ブラウザメッセージをある程度ハイジャックしたい場合にのみ、onbeforeunloadを提供する私の答えの1つです。
<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>
どんな体にも役立つかもしれないと思います。