この問題は、Chrome 21、Firefox 14、IE 7-9、Safari 5 (PC) で見つかりました。
以下は、これらすべてのブラウザで機能します。イベント中に window.onbeforeunload 関数を削除すると、2 回目の呼び出しが防止されます。秘訣は、ユーザーがページにとどまることにした場合に window.onbeforeunload 関数をリセットすることです。
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// @uses window_on_before_unload
// @param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();