0

In my webpage I want to logout a user when s/he closes the window. To capture this event I am using beforeunload event handler. But when I do close the tab the removeCookie is not called.

Here is the sample code. This is a modified code of this SO Question

var preventUnloadPrompt;
var messageBeforeUnload = "my message here - Are you sure you want to leave this page?";
$('a').live('click', function () {
    preventUnloadPrompt = true;
});
$('form').live('submit', function () {
    preventUnloadPrompt = true;
});
if ($("#refreshFlag").val() == 1) {
    preventUnloadPrompt = true;
};

$(window).bind("beforeunload", function (e) {
    var rval;
    if ($("#refreshFlag").val() == 1) {
        preventUnloadPrompt = true;
    };
    if (preventUnloadPrompt) {
        return;
    } else {
        removeCookie();
        window.location = "/";
    }
    return rval;
})

I am using JQuery 1.5.2.

What I want is when a user refresh the page it should refresh and when the tab is closed the "removeCookie" should be called. What is it that I am doing wrong in the above code?

UPDATE

As the refresh was giving problem this event was dropped from the project.

Community
  • 1
  • 1
Natraj
  • 397
  • 4
  • 9
  • 35
  • 1
    Firstly, update to a jQuery version from this decade. Secondly, what makes you think you can actually stop the user from leaving your page, and reload the page instead ? – adeneo Jul 21 '14 at 14:29

1 Answers1

0

Problem is with live() function, which is depricate from JQuery 1.7 Depricated, even though you are using older version of jquery, may be your browser is one of the latest ones, which is not alowing script execution and probably throws js error(same as my Chrome 35.0.1916.153).

All you need to do is to replace live() with on(). Below is some code snippet.

$(document).ready(function(){ debugger;
    var preventUnloadPrompt;
    var messageBeforeUnload = "my message here - Are you sure you want to leave this page?";
    $('a').on('click', function(){ preventUnloadPrompt = true; });
    $('form').on('submit', function(){ preventUnloadPrompt = true; });
    if ($("#refreshFlag").val() == 1) { preventUnloadPrompt = true; };
    $(window).on('beforeunload', function() { debugger;
        var rval;
        if ($("#refreshFlag").val() == 1) { preventUnloadPrompt = true; };
        if(preventUnloadPrompt) {
            return;
        } else {
            removeCookie();
            window.location = "/";
        }
        return rval;
    });
});
Ashish Balchandani
  • 1,228
  • 1
  • 8
  • 13