可能重复:
How to execute ajax function onbeforeunload?
How to capture browser close event and make a request to web service method on that event through javascript
所以现在这就是我的onbeforeunload看起来像
window.onbeforeunload = function (e) {
var message = "Don't close me!",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
所以这就是我正在尝试做的事情,此功能会触发并提示他们选择是否离开页面。当且仅当他们决定离开时,我需要触发GET请求来关闭数据库记录。
如果我按照以下方式进行测试:
window.onbeforeunload = $.get("url_here")
这是一个简单的修复,但是现在我无法得到提示,窗口关闭而没有警告。
我还尝试添加一个带有确认功能的功能,但它似乎无法正常工作。 E.G。
window.onbeforeunload = function(e){
if(confirm("Are you sure?")){
$.get("url_here");
return true;
}
}
这个更奇怪,但是在大多数情况下它只会导致一条消息弹出文字文本(“true”)并带有是/否提示。
答案 0 :(得分:1)
看看这个:http://jsfiddle.net/3kvAC/241和此Dialog box runs for 1 sec and disappears?以及此http://msdn.microsoft.com/en-us/library/ie/ms536907(v=vs.85).aspx
它看起来像这样:
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
$(window).unload(function(){
alert('Bye.');
});