如何检测浏览器窗口/选项卡关闭事件?

时间:2014-01-20 06:17:01

标签: javascript asp.net session

我正在尝试onbeforeunload和Unload功能。但它没有用。单击链接或刷新时,会触发此事件。我想要一个仅在浏览器窗口或选项卡关闭时触发的事件。代码必须适用于所有浏览器。

我在母版页中使用以下代码。

<script type="text/jscript">

    var leaving = true;
    var isClose = false;

    function EndChatSession() {
        var request = GetRequest();
        request.open("GET", "../Chat.aspx", true);
        request.send();
    }
    document.onkeydown = checkKeycode
    function checkKeycode(e) {
        var keycode;
        if (window.event)
            keycode = window.event.keyCode;
        else if (e)
            keycode = e.which;
        if (keycode == 116) {
            isClose = true;
        }
    }
    function somefunction() {
        isClose = true;
    }
    window.onbeforeunload = function (e) {
       if (!e) e = event;
        if (leaving) {
             EndChatSession();
             e.returnValue = "Are You Sure";

        }
    }
    function GetRequest() {
        var xmlHttp = null;
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            //Internet Explorer
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xmlHttp;
    }    
</script>

并在我的身体标签中:

以上代码适用于IE,但不适用于Chrome ...

8 个答案:

答案 0 :(得分:21)

此代码可防止复选框事件。当用户单击浏览器关闭按钮时它可以工作,但是当单击复选框时它不起作用。您可以修改其他控件(texbox,radiobutton等)

    window.onbeforeunload = function () {
        return "Are you sure?";
    }

    $(function () {
        $('input[type="checkbox"]').click(function () {
            window.onbeforeunload = function () { };
        });
    });

答案 1 :(得分:17)

您无法使用javascript检测到它。

只有检测到页面卸载/关闭的事件才是window.onbeforeunloadwindow.unload。这些事件都不能告诉您关闭页面的方式。

答案 2 :(得分:4)

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var validNavigation = false;

function wireUpEvents() {
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the    user to be able to leave withou confirmation
 var leave_message = 'ServerThemes.Net Recommend BEST WEB HOSTING at new tab  window. Good things will come to you'
 function goodbye(e) {
if (!validNavigation) {
window.open("http://serverthemes.net/best-web-hosting-services","_blank");
return leave_message;

}
}
window.onbeforeunload=goodbye;

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
 }
 });

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
  // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
});

 // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

 }

  // Wire up the events as soon as the DOM tree is ready
   $(document).ready(function() {
   wireUpEvents();
   });
   </script>

我在Can you use JavaScript to detect whether a user has closed a browser tab? closed a browser? or has left a browser?

做了回答

答案 3 :(得分:2)

你也可以这样做。

将以下脚本代码放在标题标记

<script type="text/javascript" language="text/javascript"> 
function handleBrowserCloseButton(event) { 
   if (($(window).width() - window.event.clientX) < 35 && window.event.clientY < 0) 
    {
      //Call method by Ajax call
      alert('Browser close button clicked');    
    } 
} 
</script>

从身体标签调用以上功能,如下所示

<body onbeforeunload="handleBrowserCloseButton(event);">

谢谢

答案 4 :(得分:0)

Solution Posted Here

经过初步研究,我发现当我们关闭浏览器时,浏览器将逐个关闭所有选项卡以完全关闭浏览器。因此,我观察到在关闭标签之间几乎没有时间延迟。因此,我将此时间延迟作为主要验证点,并且能够实现浏览器和选项卡关闭事件检测。

//Detect Browser or Tab Close Events
$(window).on('beforeunload',function(e) {
  e = e || window.event;
  var localStorageTime = localStorage.getItem('storagetime')
  if(localStorageTime!=null && localStorageTime!=undefined){
    var currentTime = new Date().getTime(),
        timeDifference = currentTime - localStorageTime;

    if(timeDifference<25){//Browser Closed
       localStorage.removeItem('storagetime');
    }else{//Browser Tab Closed
       localStorage.setItem('storagetime',new Date().getTime());
    }

  }else{
    localStorage.setItem('storagetime',new Date().getTime());
  }
});

JSFiddle Link

答案 5 :(得分:0)

我的解决方案类似于服务器主题提供的解决方案。进行一次检查:

localStorage.setItem("validNavigation", false);
$(document).on('keypress', function (e) {
    if (e.keyCode == 116) {
        localStorage.setItem("validNavigation", true);
    }
});

// Attach the event click for all links in the page
$(document).on("click", "a", function () {
    localStorage.setItem("validNavigation", true);
});

// Attach the event submit for all forms in the page
$(document).on("submit", "form", function () {
    localStorage.setItem("validNavigation", true);
});

// Attach the event click for all inputs in the page
$(document).bind("click", "input[type=submit]", function () {
    localStorage.setItem("validNavigation", true);
});

$(document).bind("click", "button[type=submit]", function () {
    localStorage.setItem("validNavigation", true);
});
window.onbeforeunload = function (event) {

    if (localStorage.getItem("validNavigation") === "false") {
        event.returnValue = "Write something clever here..";
        console.log("Test success!");
        localStorage.setItem("validNavigation", false);
    }
};

如果将断点正确地放置在浏览器页面上,则仅当即将关闭浏览器或选项卡即将关闭时,if条件才为真。

检查此链接以供参考:https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/

答案 6 :(得分:-1)

在刷新和关闭的标签或导航器之间做出区别,以下是我修复它的方法:

<script>
    function endSession() {
         // Browser or Broswer tab is closed
         // Write code here
    }
</script>

<body onpagehide="endSession();">

</body>

答案 7 :(得分:-2)

是的!经过很多头痛我找到了解决方法。

Monitor.php

这个php文件将监视浏览器关闭事件。一旦浏览器关闭,connection_aborted将返回1,因此循环将中断。

<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);

echo connection_aborted();
while(1)
{
echo "Whatever you echo here wont be printed anywhere but it is required in order to work.";
flush();
if(connection_aborted())
{
break;
// Breaks only when browser is closed
}
}

/*
Action you want to take after browser is closed.
Write your code here
*/
?>

Caller.php

这是调用Monitor.php的文件

<?php
Header('Location: monitor.php');
?>

Parent.html

这将是您实际与之交互的文件。在加载时,这将直接对Caller.php进行AJAX调用,这将在后台模式下自动启动Monitor.php。

<script>

 var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            }
         }

   xmlhttp.open("GET", "Caller.php", true);
        xmlhttp.send();   

</script>

所以最后的流程是Parent.html -----&gt; Caller.php -----&gt; Monitor.php