2

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

2 Answers2

6

As far as I know, a page refresh will always trigger the beforeunload since the page actually unloads. At that moment, I don't think you can detect the difference between a close and a page reload.

You can detect it at a later time, if you use local storage of some sort: javascript beforeunload detect refresh versus close

JasperZelf
  • 2,731
  • 1
  • 22
  • 34
1

The only thing that you can do is to prevent the default behaviour if the user presses the f5 key.

Please try and let me know if this works for you

        function fkey(e) {
            e = e || window.event;    
            if (e.keyCode == 116) {
                e.preventDefault();
            }   
        }

In this case, user won't be able to refresh the screen by clicking f5

Sarath P S
  • 131
  • 5