0

I'm trying to activate a page reloader preventer, and be able to deactivate the reloader preventer. In other words, I was able to show a dialog when user was about to unload/reload their page, but I'm currently looking for a way to let the user to unload/reload their page without any dialogs or warnings after a certain function has been called.

Maybe removing the event listener will help?

This is the code that I'm working with:

<!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>
  • 3
    Possible duplicate of [JavaScript: remove event listener](https://stackoverflow.com/questions/4402287/javascript-remove-event-listener) – Heretic Monkey Jun 11 '19 at 14:12

1 Answers1

5

removeEventListener works by checking the reference of the function you've passed to it, and seeing if it's been previously added by addEventListener. This means that if you want to remove a listener at a later time, you can't add it as an anonymous function - you need to have a reference to it:

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);
}
Sandy Gifford
  • 7,219
  • 3
  • 35
  • 65