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