Search code examples
javascriptonbeforeunload

How to prevent window.onbeforeunload event being triggered by button and links events


My form contains multiple buttons and hyperlinks and i want to show alert on back button of browser. I have used below code which works fine on Chrome and Safari but not working in IE and Firefox:

       window.onload = function() {

            var btnClicks = document.getElementsByClassName('noPopup');
            var links = document.getElementsByTagName('a');

            for (var i = 0; i < links.length; i++) {
                links[i].onclick = setGlobal;
            }
            for (var i = 0; i < btnClicks.length; i++) {
                btnClicks[i].onclick = setGlobal;
            }
            function setGlobal() {
                window.btn_clicked = true;
                window.linkClicked = true;
            }

              window.onbeforeunload = function() {
                  if (!window.btn_clicked || !window.linkClicked) {
                      return 'Would you like to save first.';
                  }
              };

      };

Solution

  • in IE - if you don't want the onbeforeunload to trigger - all you need to do is to set this event to null, like this:

    window.onbeforeunload = null;
    

    so what you would have to do is - add a click event listener to all your buttons and links (which redirect user to a different URI) and inside that listener - set the onbeforeunload event listener to null once they are clicked (before proceeding with the normal link/button action. Otherwise - set it to function (like you have in your code).

    e.g.:

    document.getElementById('myLink').onclick = function () {
        window.onbeforeunload = null;
    };