Crossbrowser onbeforeunload?

pow*_*tac 37 javascript cross-browser onbeforeunload

难道window.onbeforeunload()火在所有浏览器?我需要一个至少由IE6和FF3.6支持的onbeforeunload功能.

对于IE,onbeforeunload()似乎只有IE9支持

Ael*_*ios 14

我找到了Firefox的setTimeout功能解决方法,因为它与其他Web浏览器没有相同的行为.

window.onbeforeunload = function (e) {
    var message = "Are you sure ?";
    var firefox = /Firefox[\/\s](\d+)/.test(navigator.userAgent);

    if (firefox) {
        //Add custom dialog
        //Firefox does not accept window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() furthermore
        var dialog = document.createElement("div");
        document.body.appendChild(dialog);
        dialog.id = "dialog";
        dialog.style.visibility = "hidden";
        dialog.innerHTML = message; 
        var left = document.body.clientWidth / 2 - dialog.clientWidth / 2;
        dialog.style.left = left + "px";
        dialog.style.visibility = "visible";  
        var shadow = document.createElement("div");
        document.body.appendChild(shadow);
        shadow.id = "shadow";       
        //tip with setTimeout
        setTimeout(function () {
            document.body.removeChild(document.getElementById("dialog"));
            document.body.removeChild(document.getElementById("shadow"));
        }, 0);
    }

    return message;
}
Run Code Online (Sandbox Code Playgroud)

GitHub:https://github.com/Aelios/crossbrowser-onbeforeunload


Ian*_*way 5

不,它不会在所有浏览器中触发.移动浏览器不支持它,例如Safari,Opera Mobile和mini,Dolphin.请参阅在移动Safari中使用onbeforeunload有替代方法吗?

  • 虽然我一般同意,在这种情况下,我的答案确实包括链接文章的基本部分(移动浏览器不支持),加上我链接到SO所以没有链接变得无效的危险. (2认同)

Bra*_*tie 1

我记得IE是唯一实现它的浏览器onbeforeunload,但有些浏览器自己也实现了它。

长话短说,IE 是唯一可以始终如一地发现此事件的浏览器(除了非常有限的例外)。