好吧,我对以下代码有疑问。当用户关闭浏览器时,它应该提示他们单击“确定”或单击“取消”退出页面。单击“确定”将触发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...");
}
}
答案 0 :(得分: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';
}
然而,你是否依赖于webbrowser是否实际上命中服务器。大多数(如果不是全部)网络浏览器都没有。我宁愿在该URL上发出一个ajaxical请求,但你是否依赖webbrowser它是否能完美运行。
答案 1 :(得分:0)
也许不是劫持用户的浏览器,你可以从unbeforeunload()中发出XHR请求,并将你需要的数据发送到你需要的地方?
如果没有更多的用例,很难说,但这可能是一个不错的选择。
答案 2 :(得分: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);