javascript - 如何在 JavaScript 中停用 beforeunload 事件监听器
问题描述
我正在尝试激活页面重新加载阻止程序,并能够停用重新加载阻止程序。换句话说,当用户即将卸载/重新加载他们的页面时,我能够显示一个对话框,但我目前正在寻找一种方法让用户在特定功能后卸载/重新加载他们的页面而没有任何对话框或警告已被调用。
也许删除事件监听器会有所帮助?
这是我正在使用的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button onclick="activateReloader()">activate</button>
<button onclick="deactivateReloader()">deactivate</button>
<script>
function activateReloader() {
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
});
}
function deactivateReloader() {
window.removeEventListener('beforeunload', function (e) {});
}
</script>
</body>
</html>
解决方案
removeEventListener
通过检查您传递给它的函数的引用来工作,并查看它是否以前由addEventListener
. 这意味着,如果您想在以后删除某个侦听器,则不能将其添加为匿名函数 - 您需要对其进行引用:
function onBeforeUnload(e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
}
function activateReloader() {
window.addEventListener('beforeunload', onBeforeUnload);
}
function deactivateReloader() {
window.removeEventListener('beforeunload', onBeforeUnload);
}
推荐阅读
- python - Beautifulsoup 查找某个孩子下的所有孩子
- python - 获取除 url 中的所有非单词字符
- java - 我在 Android Studio 上的应用无法使用 JVM 1.8 编译
- javascript - DeprecationWarning:消息事件已被弃用。改用 messageCreate
- angular - Angular this.router 即使在构造函数中声明也是未定义的
- node.js - customHooks module.exports 未使用 es6 样式导入
- javascript - 如何过滤和排序嵌套对象?反应JS
- apache-spark - 索引集合中的大量数据时 SOLR 读取超时(套接字连接超时)
- android - 未解决的参考:Android S 的 LocationRequest (12)
- azure - 在 Azure 应用程序网关中包含 Letsencrypt 根证书