首页 > 解决方案 > 如何在 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>

标签: javascripthtml

解决方案


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);
}

推荐阅读