javascript判断窗口关闭事件

<script language=javascript>
function window.onbeforeunload()
{
if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey||event.ctrlKey)
{
//判断event.altKey是为了Alt+F4关闭的情况;判断event.ctrlKey是为了Ctrl+W关闭的情况
//document.body.clientWidth不包括滚动条,而关闭按钮恰好在滚动条右侧。
window.event.returnValue="";
}
}
</script>

1、浏览器不是软件的窗口,要该事件非常困难,因为关闭与刷新这两个事件就很难区分。

2、都没有对应的事件,只能根据一些条件来判断,但未必准确。

3、前进、后退、刷新、关闭都响应事件window.onbeforeunload。

4、javascript之所以能得到某些事件属性和调用方法,是因为浏览器对象为他提供了接口,用COM的术语来说,是IDispatch接口,如果浏览器对象没有为他提供接口,他什么也干不了。所以有些功能在其它语言中可以实现,而在javascript中是永远无法实现的。

用onUnload方法

在body 标签里加入onUnload事件

body onUnload="myClose()"

然后在javascript里定义myClose()方法,但是onUnload方法是在关闭窗口之后执行,不是在关闭窗口之前执行,如果你想在关闭窗口之前做判断,请用第一种方法

function getEvent() //同时兼容ie和ff的写法, 这个方法是网上copy的  
{
if(document.all) return window.event;
func=getEvent.caller;
while(func!=null){
var arg0=func.arguments[0];
if(arg0)
{
if((arg0.constructor==Event || arg0.constructor ==MouseEvent)
                || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation)) 
{
return arg0;
}
}
func=func.caller;
}
return null;
}

function ConfirmClose(){
if(window.event){
window.event.returnValue = "在关闭窗口前确认您是否已经保存了信息!";
}else{
getEvent().preventDefault();//for firefox
}
}
function on_page_loaded(){//自己定义的body的onload事件
try{
if(!window.onbeforeunload){ //为了不覆盖原来的onbeforeunload方法,先判断
window.onbeforeunload = ConfirmClose; //todo 增加了窗口关闭前的提示
}
}catch(e){}
}
<body onload="on_page_loaded()">

//打开窗体应先判断父窗体是否关闭

function rsSeek(){
if(opener){
if(typeof(window.opener.document)=='unknown' ||typeof(window.opener.document) == 'undefined'){
//已关闭
}else{
opener.MySeekOk();
}
}
}