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

时间:2023-01-05 07:16:12

I am Trying with onbeforeunload, and Unload function. But it didn't work. When clicking a link or refreshing, this event got triggered. I want an event that is triggered only when a browser window or tab is closed. The code must work in all browsers.

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

I am using Following code in Masterpage.

我在Masterpage中使用以下代码。

<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>

and in my body tag:

并在我的身体标签:

The Above code works in IE but not in chrome...

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

6 个解决方案

#1


19  

This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)

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

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

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

#2


14  

You can't detect it with javascript.

您无法使用javascript检测到它。

Only events that do detect page unloading/closing are window.onbeforeunload and window.unload. Neither of these events can tell you the way that you closed the page.

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

#3


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>

I did answer at Can you use JavaScript to detect whether a user has closed a browser tab? closed a browser? or has left a browser?

我确实回答你是否可以使用JavaScript来检测用户是否已关闭浏览器选项卡?关闭浏览器?或者已经离开了浏览器?

#4


2  

You can also do like below.

你也可以这样做。

put below script code in header tag

将下面的脚本代码放在标题标记中

<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>

call above function from body tag like below

从下面的body标签调用上面的函数

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

Thank you

谢谢

#5


-1  

to make the difference between a refresh and a closed tab or navigator, here is how I fixed it :

为了区分刷新和关闭的选项卡或导航器,以下是我修复它的方法:

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

<body onpagehide="endSession();">

</body>

#6


-2  

Yes there is! After a lot of headache i found one solution to this.

就在这里!经过很多头痛我找到了一个解决方案。

Monitor.php

Monitor.php

This php file will be monitoring the browser close event. Once the browser is closed the connection_aborted will return 1 hence the loop will break.

这个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

Caller.php

This is the file which will call Monitor.php

这是调用Monitor.php的文件

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

Parent.html

Parent.html

This will be the file which you will actually interact with. On loading this will directly make an AJAX call to Caller.php which will automatically start Monitor.php in background mode.

这将是您实际与之交互的文件。在加载时,这将直接对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>

So the final flow is Parent.html----->Caller.php----->Monitor.php

所以最后的流程是Parent.html -----> Caller.php -----> Monitor.php

#1


19  

This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)

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

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

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

#2


14  

You can't detect it with javascript.

您无法使用javascript检测到它。

Only events that do detect page unloading/closing are window.onbeforeunload and window.unload. Neither of these events can tell you the way that you closed the page.

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

#3


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>

I did answer at Can you use JavaScript to detect whether a user has closed a browser tab? closed a browser? or has left a browser?

我确实回答你是否可以使用JavaScript来检测用户是否已关闭浏览器选项卡?关闭浏览器?或者已经离开了浏览器?

#4


2  

You can also do like below.

你也可以这样做。

put below script code in header tag

将下面的脚本代码放在标题标记中

<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>

call above function from body tag like below

从下面的body标签调用上面的函数

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

Thank you

谢谢

#5


-1  

to make the difference between a refresh and a closed tab or navigator, here is how I fixed it :

为了区分刷新和关闭的选项卡或导航器,以下是我修复它的方法:

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

<body onpagehide="endSession();">

</body>

#6


-2  

Yes there is! After a lot of headache i found one solution to this.

就在这里!经过很多头痛我找到了一个解决方案。

Monitor.php

Monitor.php

This php file will be monitoring the browser close event. Once the browser is closed the connection_aborted will return 1 hence the loop will break.

这个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

Caller.php

This is the file which will call Monitor.php

这是调用Monitor.php的文件

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

Parent.html

Parent.html

This will be the file which you will actually interact with. On loading this will directly make an AJAX call to Caller.php which will automatically start Monitor.php in background mode.

这将是您实际与之交互的文件。在加载时,这将直接对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>

So the final flow is Parent.html----->Caller.php----->Monitor.php

所以最后的流程是Parent.html -----> Caller.php -----> Monitor.php