0

I tried to detect a tap close event and get a confirmation message. The code is like this. Strangely, if I close the tab after the mouse event occurs(clicking anywhere), the confirmation message appears normally, but if the mouse event does not occur, the message window does not appear and just appears. What is the difference between a mouse event occurring and not occurring after the page is loaded?

$(function(){
    var validNavigation = false;
    //Attach the event keypress to exclude the F5 refresh (includes normal refresh)
    $(document).bind('keypress', function (e) {
        if (e.keyCode == 116) {
            validNavigation = true;
        }
    });

    // Attach the event click for all links in the page
    $("a").bind("click", function () {
        validNavigation = true;
    });

    // Attach the event submit for all forms in the page
    $("form").bind("submit", function () {
        validNavigation = true;
    });

    // Attach the event click for all inputs in the page
    $("input[type=submit]").bind("click", function () {
        validNavigation = true;
    });

    window.onbeforeunload = function () {
        if (!validNavigation) {
            return "Do you really want to close?"; 
        }
        validNavigation = false;
    };

});
Hello
  • 1
  • *the message window does not appear and just appears* Huh? – connexo Nov 28 '21 at 09:16
  • Regarding the duplicate closure, I am sorry this is not a perfect one, https://stackoverflow.com/questions/51497294/onbeforeunload-before-any-interaction-with-the-dom is, but was answered in the comments and thus can't be a correct target. However the accepted answer in the linked question does have the key point to your issue: the user must interact with the page for this message to show, it's intended to prevent unsaved changes, if the user didn't interact with the page, there is obviously no changes that could have been made by them. – Kaiido Nov 28 '21 at 10:15
  • @connexo yes! depending on whether mouse click happened or not – Hello Nov 28 '21 at 16:55
  • @Kaiido oh! it seems the comment fits in my case. thank you! – Hello Nov 28 '21 at 16:58

0 Answers0