我正在写一个JS,这是一个插件使用。JS有一个onbeforeunload事件。
我需要一些建议,这样我的onbeforeunload事件就不会覆盖现有的onbeforeunload事件(如果有的话)。我可以将我的onbeforeunload附加到现有的onbeforeunload吗?
谢谢。
发布于 2012-01-25 16:18:52
如果您不使用事件观察,而是直接附加onbeforeunload处理程序(您不应该这样做),则只需要注意这一点。如果是这样的话,使用类似的代码来避免覆盖现有的处理程序。
(function() {
var existingHandler = window.onbeforeunload;
window.onbeforeunload = function(event) {
if (existingHandler) existingHandler(event);
// your own handler code here
}
})();不幸的是,您不能阻止其他(稍后)脚本覆盖您的处理程序。但同样,这可以通过添加事件侦听器来解决:
$(window).unload(function(event) {
// your handler code here
});发布于 2019-11-14 00:31:05
我觉得这个问题没有得到完全的回答,因为没有使用addEventListener的例子(但MAZZTer指出了addEventListener解决方案)。我的解决方案与Julian D相同,但不使用jQuery,仅使用原生javascript。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Before Unload</title>
</head>
<body>
<p>Test</p>
<script>
window.addEventListener('beforeunload', function (event) {
console.log('handler 1')
event.preventDefault()
event.returnValue = ''
});
window.addEventListener('beforeunload', function (event) {
console.log('handler 2')
});
</script>
</body>
</html>在这个例子中,两个监听器都将被执行。如果设置了任何其他beforeunload侦听器,则不会覆盖它们。我们将得到以下输出(不保证顺序):
handler 1
handler 2而且,重要的是,如果一个或多个事件侦听器执行event.preventDefault(); event.returnValue = '',则会出现一个提示,询问用户是否真的要重新加载。
如果您正在编辑表单,同时通过ajax下载文件,并且不想丢失其中任何操作的数据,这将非常有用。它们中的每一个都可以有一个侦听器来防止页面重新加载。
const editingForm = function (event) {
console.log('I am preventing losing form data')
event.preventDefault()
event.returnValue = ''
}
const preventDownload = function (event) {
console.log('I am preventing a download')
event.preventDefault()
event.returnValue = ''
}
// Add listener when the download starts
window.addEventListener('beforeunload', preventDownload);
// Add listener when the form is being edited
window.addEventListener('beforeunload', editingForm);
// Remove listener when the download ends
window.removeEventListener('beforeunload', preventDownload);
// Remove listener when the form editing ends
window.removeEventListener('beforeunload', editingForm);发布于 2014-12-25 12:07:54
我的想法是:
var callbacks = [];
window.onbeforeunload = function() {
while (callbacks.length) {
var cb = callbacks.shift();
typeof(cb)==="function" && cb();
}
}和
callbacks.push(function() {
console.log("callback");
});https://stackoverflow.com/questions/8999439
复制相似问题