判断用户关闭浏览器-beforeunload事件

来源:互联网 发布:出国翻译官软件 编辑:程序博客网 时间:2024/05/16 15:33

用beforeunload事件,在某些浏览器上(chrome、ie、firefox)可以监听到浏览器关闭操作,能够在关闭之前,弹出一个对话框,让用户选择是否关闭。代码如下:

1
2
3
4
5
6
7
//提示用户是否离开此页面(关闭、刷新或者点击后退等)
window.addEventListener("beforeunload"function (e) {
  var confirmationMessage = '确定离开此页吗?本页不需要刷新或后退';
 
  (e || window.event).returnValue = confirmationMessage;     // Gecko and Trident
  return confirmationMessage;                                // Gecko and WebKit
});


注意:该对话框只能起到提示、阻止关闭作用,如果用户选择 “YES” 关闭浏览器,我们无法在js中获得回调值。

参见mozilla官方文档:https://developer.mozilla.org/zh-CN/docs/Web/Events/beforeunload


End.


1 0
原创粉丝点击