Search code examples
javascriptbuttononbeforeunload

Disable JS beforeunload if button with specific id has been clicked


Problem:

I have a beforeunload warning sign that is activated if the user try to navigate away from the webpage. I wish to disable this behavior if a user press a specific button.

JS:

window.addEventListener("beforeunload", function (e) {
    var confirmationMessage = "Not a good idea - want to reconsider?";

    (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
});

HTML:

<a href="survey.php" class="btn btn-primary" id="initiatesurvey">Next</a>

Desired output:

To be able to click the next-button without beforeunload gets activated. I have seen a number of solutions on SO but I am looking for a solution that is pure JS.


Solution

  • Remove the event listener when they push the button. To do this, you need to use a named function rather than an anonymous function, so you can refer to it when calling removeEventListener.

    function beforeUnload(e) {
      var confirmationMessage = "Not a good idea - want to reconsider?";
    
      (e || window.event).returnValue = confirmationMessage; //Gecko + IE
      return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
    
    }
    
    window.addEventListener("beforeunload", beforeUnload);
    
    document.getElementById("initiatesurvey").addEventListener("click", function() {
      window.removeEventListener("beforeunload", beforeUnload);
    });