我需要在用户离开页面之前警告他们关于未保存的更改(这是一个非常常见的问题)。
window.onbeforeunload = handler
这是可行的,但它会引发一个默认对话框,其中包含一个烦人的标准消息,其中包装了我自己的文本。我需要完全替换标准消息,这样我的文本是清晰的,或者(甚至更好)用jQuery的模态对话框替换整个对话框。
到目前为止,我失败了,我还没有找到其他似乎有答案的人。这可能吗?
Javascript在我的页面:
<script type="text/javascript">
window.onbeforeunload = closeIt;
</script>
closeIt()函数:
function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
使用jQuery和jqModal我已经尝试了这种事情(使用自定义确认对话框):
$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
这也不工作-我似乎不能绑定到beforeunload事件。
1)使用onbeforeunload,而不是onunload。
2)重要的是避免执行return语句。我这么说不是为了避免从你的联络人那里回来。你可以返回,但你要确保你到达了函数的结尾,并且不执行return语句。在这些条件下,不会出现内置的标准对话框。
3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.
虽然在某些情况下对该方框无能为力,但您可以拦截点击链接的人。对我来说,这对于大多数情况来说都是值得的,作为备用方案,我留下了unload事件。
我使用的是Boxy而不是标准的jQuery Dialog,它可以在这里获得:http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
您可以附加到另一个事件,并根据单击的锚的类型筛选更多内容,但这对我和我想做的事情都有效,并可作为其他人使用或改进的示例。我想把这个分享给那些想要这个解决方案的人。
我已经剪掉了代码,所以这可能无法正常工作。
You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.
function onunload = (){
window.open('logout.php');
}
此代码在用户离开页面或关闭活动窗口时调用,用户通过'logout.php'退出。
注销php时,新窗口立即关闭:
window.close();