日期:2014-05-17  浏览次数:21190 次

如何用JS判断浏览器刷新还是关闭?
HTML code
 var currentKeyCode = -1;

    function document.onkeydown() { // 本窗口的所有下属页面都必须含有本函数

       top.currentKeyCode = event.keyCode;
    }


    function window.onbeforeunload() {

        var sw = 0, s0 = "";
        if (currentKeyCode == 116) 
        {
           s0 += "刷新窗口!(F5)";
        }
        else 
        {
           if ((event.altKey)&&(currentKeyCode == 115)) 
            {
                  s0 += "关闭窗口!(alt+F4)"; sw = 1;
            }
            else 
            {
               if ((event.clientX > 0)&&(event.clientX < document.body.clientWidth)) 
               {
                  s0 += "刷新窗口!";
               }
               else 
               {
                  s0 += "关闭窗口!"; sw = 1;
               }
            }
        }
        if (sw == 1) 
        {
          event.returnValue = "";
        }
        else 
        {
          currentKeyCode = -1;
        }
    }

这是我从网上找的一段JS代码,用浏览器右上角的关闭按钮时好用,但在选项卡上关闭和在任务栏上关闭,这个方法就不作用了,我用的是IE8

------解决方案--------------------
帮顶一个
------解决方案--------------------
window对象是不是有个onclosing事件啊?
------解决方案--------------------
不明白 学习
------解决方案--------------------
我记得windows是有一个关闭事件的。
------解决方案--------------------
探讨
window对象是不是有个onclosing事件啊?

------解决方案--------------------
这个不懂 帮顶
------解决方案--------------------
js标签只有onload\onunload\onbeforeunload事件,而没有onclose事件。

不管页面是关闭还是刷新都会执行onunload事件。

如何捕捉到页面关闭呢? 
页面加载时只执行onload 
页面关闭时只执行onunload 
页面刷新时先执行onbeforeunload,然后onunload,最后onload。

这样我们可以在onbeforeunload中加一个标记,在onunload中判断该标记,即可达到判断页面是否真的关闭了。

1、Js代码 
1.window.onbeforeunload = function() {
2.
3.var n = window.event.screenX - window.screenLeft;
4.
5.var b = n > document.documentElement.scrollWidth-20;
6.
7.
8.if(b && window.event.clientY < 0 || window.event.altKey) {
9.
10.alert("是关闭而非刷新");
11.
12.window.open(this.location);
13.
14.
15.//return false;
16.
17.//window.event.returnValue = ""; }
18.
19.} else{
20.
21.alert("是刷新而非关闭");
22.
23.}
24.
25.}
window.onbeforeunload = function() { 

var n = window.event.screenX - window.screenLeft; 

var b = n > document.documentElement.scrollWidth-20; 


if(b && window.event.clientY < 0 || window.event.altKey) { 

alert("是关闭而非刷新"); 

window.open(this.location);


//return false;

//window.event.returnValue = ""; } 

} else{

alert("是刷新而非关闭"); 

}

}
 

2、

Js代码 
1.function promptOnClose(e){
2.
3.//e = e ? e : windowevent;
4.
5.var promptString = '你是否要离开此页面,离开该页面的信息将不被保存!';
6.
7.//event.returnValue = promptString;
8.
9.return promptString;
10.
11.}
12.
13.if (window != top){
14.
15.top.location.href = "www.baidu.com";
16.
17.}else{
18.
19.if (window.Event) {
20.
21. window.onbeforeunload = function(event) {