开发者

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 开发者_JAVA百科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...");
    }
}


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.


Perhaps instead of hijacking the user's browser you could fire an XHR request from inside your unbeforeunload() and get the data you need sent over to where you need it?

Without more of the use-case it's hard to tell, but this may provide a nice alternative.


Tested in IE9 and Chrome


function addEvent(elm, evType, fn, useCapture) {
  if (elm.addEventListener) {
    elm.addEventListener(evType, fn, useCapture);
    return true;
  }
  else if (elm.attachEvent) {
    var r = elm.attachEvent('on' + evType, fn);
    return r;
  }
  else {
    elm['on' + evType] = fn;
  }
}

function exitAlert(e) {
  var msg = "This message will appear in the dialog.";
  if (!e) { e = window.event; }
  if (e) { e.returnValue = msg; }
  return msg;
}

addEvent(window, 'beforeunload', exitAlert, false);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜