window.onbeforeunload should be fire for window close event only not for other event like back,reload page

1.3k Views Asked by At

I want to destroy session only when browse is close. I am using window.onbeforeunload function but it fired on below cases:

  1. page redirection by link navigation,form submission or window.location function
  2. F5 or CTRL+F5 press
  3. CTRL+R, CTRL+SHIFT+R press
  4. When click on reload button of the browser
  5. focus on URL typing box and press enter
  6. When close the browser

I want to do somthing(Make ajax call) only for 6th case.

For case 1,2,3 my code working properly but what i need to do for case 4 & 5.

My code Below:

var isOK = true;
        $(document).bind('keydown', function(e) {
            if (e.keyCode == 116){
                isOK = false;
            }
            if (e.keyCode == 82 && e.ctrlKey) {
                isOK = false;
            }
            if (e.keyCode == 82 && e.shiftKey && e.ctrlKey) {
                isOK = false;
            }
        });
        window.onbeforeunload = function(event) {
            if(isOK)
            {
                $.ajax({
                    url: "server.jsp",
                    type: "POST",
                    data: "KillSession"
                });
                alert("Your session is expired!!!");
            }else{
                alert("onbeforeunload call!!! but ajax not call");
            }
        };
0

There are 0 best solutions below