5

我对以下代码有疑问。发生的情况是当用户关闭浏览器时,它应该提示他们单击“确定”或单击“取消”以离开页面。单击“确定”将触发window.location重定向到另一个页面以进行用户跟踪(是的,为了避免激战,有一个辅助系统来确保准确跟踪,以防用户从任务管理器中杀死浏览器(如前所述在类似的问题中))。CANCEL 将保留在页面上,问题是无论您点击什么按钮,您都会被重定向,就好像您想离开页面一样。相关代码如下。

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...");
    }
}
4

3 回答 3

6

onbeforeunload那样不行。相关函数应返回一个字符串,该字符串依次显示在默认onbeforeunload对话框中。

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

但是您不会返回任何东西并使用confirm(). 当函数不返回任何内容时,onbeforeunload对话框将根本不显示。

要调用真正的注销,您需要使用该onunload事件。这是一个重写:

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

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

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

但是,您依赖于网络浏览器,最后一个是否会实际访问服务器。大多数(如果不是全部)网络浏览器都没有。我宁愿在那个 URL 上发出一个 ajaxical 请求,但你也依赖于网络浏览器,它是否能完美运行。

于 2010-06-17T00:40:48.960 回答
0

也许您可以从 unbeforeunload() 内部触发 XHR 请求,而不是劫持用户的浏览器,并将您需要的数据发送到您需要的地方?

如果没有更多的用例,很难说,但这可能会提供一个不错的选择。

于 2010-06-17T00:37:16.253 回答
0

在 IE9 和 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);
于 2012-01-24T16:07:18.567 回答