防止使用 JavaScript 浏览网页

如何防止网页使用 JavaScript 导航?

166106 次浏览

使用 卸货

对于 jQuery,我认为它是这样工作的:

$(window).unload(function() {
alert("Unloading");
return falseIfYouWantToButBeCareful();
});

在 Ayman 的例子中,通过返回 false 可以阻止浏览器窗口/选项卡关闭。

window.onunload = function () {
alert('You are trying to leave.');
return false;
}

使用 onunload允许显示消息,但不会中断导航(因为为时已晚)。但是,使用 onbeforeunload会中断导航:

window.onbeforeunload = function() {
return "";
}

注意: 返回一个空字符串是因为较新的浏览器提供了一条消息,比如“任何未保存的更改将丢失”,这条消息不能被覆盖。

在较老的浏览器中,您可以指定要在提示符中显示的消息:

window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}

建议的错误消息可能会重复浏览器已经显示的错误消息。在 chrome 中,两个相似的错误信息在同一个窗口中一个接一个地显示出来。

在 chrome 中,自定义消息后显示的文本是: “您确定要离开此页面吗?”.在 firefox 中,它根本不显示我们的自定义错误消息(但仍然显示对话框)。

更合适的错误消息可能是:

window.onbeforeunload = function() {
return "If you leave this page, you will lose any unsaved changes.";
}

或者 stackoverflow 风格: “你已经开始写作或编辑一篇文章。”

与这里介绍的其他方法不同,这段代码将 没有导致浏览器显示一个警告,询问用户是否想离开; 相反,它利用 DOM 的事件特性重定向回当前页面(从而取消导航) ,在浏览器有机会从内存中卸载它之前。

由于它的工作原理是直接短路导航,所以不能用来防止页面被关闭; 但是,它可以用来禁用帧破坏。

(function () {
var location = window.document.location;


var preventNavigation = function () {
var originalHashValue = location.hash;


window.setTimeout(function () {
location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
location.hash = originalHashValue;
}, 0);
};


window.addEventListener('beforeunload', preventNavigation, false);
window.addEventListener('unload', preventNavigation, false);
})();

免责声明: 你永远不应该这样做。如果页面上有帧破坏代码,请尊重作者的意愿。

我最终得到了略有不同的版本:

var dirty = false;
window.onbeforeunload = function() {
return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}

在其他地方,当表单被弄脏时,我将脏标志设置为 true (或者我想防止导航离开)。这使我能够轻松地控制用户是否获得确认导航提示。

在选定的答案中,你会看到多余的提示:

enter image description here

相当于 jQuery 1.11中接受的答案:

$(window).on("beforeunload", function () {
return "Please don't leave me!";
});

JSFiddle 的例子

AltCognto 的回答使用了 unload事件,这个事件发生得太晚,JavaScript 无法中止导航。

使用现代的 addEventListener API,以更现代和浏览器兼容的方式实现等效。

window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});

资料来源: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

如果你正在捕捉一个 浏览器的后退/前进按钮并且不想导航离开,你可以使用:

window.addEventListener('popstate', function() {
if (window.location.origin !== 'http://example.com') {
// Do something if not your domain
} else if (window.location.href === 'http://example.com/sign-in/step-1') {
window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
} else if (window.location.href === 'http://example.com/sign-in/step-2') {
window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
} else {
// Let it do its thing
}
});

否则,您可以使用 在卸货之前事件,但是消息可能跨浏览器工作,也可能不工作,并且需要返回一些强制执行内置提示符的内容。

如果需要在退出时将状态切换回 没有通知,请使用以下代码行:

window.onbeforeunload = null;