Question

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

      };
Was it helpful?

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top