Monday, 2 December 2019

Prevent beforeunload event from browser reload button click

I have a script which executes on page beforeunload to trigger a web method on tab close / browser close. functionality of this script is to trigger a webmethod on a page beforeunload. i wanted to prevent the script method from executing on f5 button click and able to do that. but now i need to prevent the script method from executing on browser reload button click (mostly chrome) but could'nt do it. i have shared the script below. any suggestion is much appreciated.

       var IsFunction5KeyPressed = false;

        // .... Tab & Browser Close Events ....
        $(window).bind('beforeunload', function (e) {
            if (!IsFunction5KeyPressed) {                  
                $.ajax({
                    type: "POST",
                    url: "Page.aspx/WebMethod1",
                    data: '{name: "' + "test" + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function () { IsFunction5KeyPressed = false;  },
                    error: function (response) { }
                });
            }
        });

        document.onkeydown = fkey;
        document.onkeypress = fkey
        document.onkeyup = fkey;

        var wasPressed = false;

        function fkey(e) {
            e = e || window.event;
            if (wasPressed) return;

            if (e.keyCode == 116) {
                IsFunction5KeyPressed = true
                wasPressed = true;
            }   
        }


from Prevent beforeunload event from browser reload button click

No comments:

Post a Comment