Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onbeforeunload Issue

I have an issue with the following code. What happens is when a user closes their browser, it should prompt them to either click OK or click CANCEL to leave the page. Clicking OK would trigger a window.location to redirect to another page for user tracking (and yes, to avoid flame wars, there is a secondary system in place to assure accurate tracking, in the event of the user killing the browser from the task manager (as mentioned in similar questions)). CANCEL would remain on the page, the issue being that no matter what button you hit, you get redirected as if you wanted to leave the page. The relevant code is below.

window.onbeforeunload = confirmExit;
function confirmExit()
{
    var where_to = confirm("Click OK to exit, Click CANCEL to stay.");
    if (where_to == true)
    {
        window.location="logout.php";
    }
    if (where_to == false){
        alert("Returning...");
    }
}
like image 308
Nik Avatar asked Jun 17 '10 00:06

Nik


1 Answers

The onbeforeunload doesn't work that way. The associated function should return a string which is in turn to be displayed on the default onbeforeunload dialog.

function confirmExit() {
    return "This message will appear in the dialog.";
}

But you aren't returning anything and taking it in your own hands with a confirm(). When the function doesn't return anything, then the onbeforeunload dialog won't be displayed at all.

To invoke the real logout, you'd like to use the onunload event. Here's a rewrite:

window.onbeforeunload = confirmExit;
window.onunload = logout;

function confirmExit() {
    return "Click OK to exit, Click CANCEL to stay.";
}

function logout() {
    window.location = 'logout.php';
}

You're however dependent on the webbrowser whether the last will actually hit the server. Most if not all of the webbrowsers don't. I'd rather fire an ajaxical request on that URL, but you're dependent on the webbrowser as well whether it will work flawlessly.

like image 151
BalusC Avatar answered Sep 22 '22 21:09

BalusC