MJVDM
MJVDM

Reputation: 3963

Do something before the user closes the tab/window

I tried window.onbeforeunload but it doesn't seem to work. Any help?

I have a cookie that tracks if the user logged in.

function handleLoginRegSuccess(){
    $.cookie('loginStatus', "ON", { expires: 1, path: '/'});
    showBusyMessage();
    goToIndex();
}

This is what I tried, but it doesnt work.

window.onbeforeunload = function(e) {
    if(userLoginStatus()=="ON"){
        requestLogout();
        $.removeCookie('loginStatus');
        return "test";
    }
};

Upvotes: 2

Views: 1894

Answers (1)

Paul
Paul

Reputation: 36319

So, to answer your question directly, onbeforeunload needs a return value to actually work, at which point it'll prompt the user with that string and they'll get a confirm box.

More details in this stack answer: How can I override the OnBeforeUnload dialog and replace it with my own?

What you might consider instead, is to have a session timeout that logs the person out, or (more aggressively) a heartbeat from the client that keeps them logged in (via ajax). When the heartbeat fails to fire, they get logged out.

You can also use the onunload event, if you're not trying to interact w/ the user at all (as your sample code seems to not do): http://msdn.microsoft.com/en-us/library/ie/ms536973(v=vs.85).aspx

Upvotes: 2

Related Questions