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

StackOverflow https://stackoverflow.com/questions/17831525

  •  04-06-2022
  •  | 
  •  

Вопрос

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.';
                  }
              };

      };
Это было полезно?

Решение

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

Другие советы

Using this beforeunload will occur only on browser close neither occur on refresh of any click of anchor and also it will act as unload event by excluding return for hiding built-in popup message on before unload event

    function confirmExit()
    {
        $.ajax({
            type: "POST",
            url: site_url + 'welcome_login/logout',
            success: function (data)
            {
            }
        });
    }
    $(window).on('mouseover', (function () {
        window.onbeforeunload = null;
    }));
    $(window).on('mouseout', (function () {
        window.onbeforeunload = confirmExit;
    }));

Mouse Out Occurs on Closing Browser window

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top