简体   繁体   English

如何检测浏览器窗口/标签关闭事件?

[英]How to Detect Browser Window /Tab Close Event?

I am Trying with onbeforeunload, and Unload function.我正在尝试使用 onbeforeunload 和 Unload 功能。 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.代码必须适用于所有浏览器。

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 中无效...

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.)您可以为其他控件(文本框、单选按钮等)修改它

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

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

You can't detect it with javascript.您无法使用 javascript 检测到它。

Only events that do detect page unloading/closing are window.onbeforeunload and window.unload .只有检测页面卸载/关闭的事件是window.onbeforeunloadwindow.unload Neither of these events can tell you the way that you closed the page.这些事件都不能告诉您关闭页面的方式。

<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?我在Can you use JavaScript to detect a user 是否关闭了浏览器选项卡? closed a browser? 关闭浏览器? or has left a browser? 还是离开了浏览器?

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

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>

Solution Posted Here解决方案张贴在这里

After my initial research i found that when we close a browser, the browser will close all the tabs one by one to completely close the browser.经过初步研究,我发现当我们关闭浏览器时,浏览器会一一关闭所有选项卡以完全关闭浏览器。 Hence, i observed that there will be very little time delay between closing the tabs.因此,我观察到关闭选项卡之间的时间延迟非常小。 So I taken this time delay as my main validation point and able to achieve the browser and tab close event detection.所以我把这个时间延迟作为我的主要验证点,并且能够实现浏览器和选项卡关闭事件的检测。

//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 JSFiddle 链接

my solution is similar to the solution given by Server Themes.我的解决方案类似于服务器主题给出的解决方案。 Do check it once:检查一次:

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 you put the breakpoints correctly on the browser page, the if condition will be true only when the browser is about to be closed or the tab is about to be closed.如果在浏览器页面上正确放置断点,则仅当浏览器即将关闭或选项卡即将关闭时,if 条件才会为真。

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

Yes there is!就在这里! After a lot of headache i found one solution to this.经过很多头痛,我找到了一个解决方案。

Monitor.php监视器.php

This php file will be monitoring the browser close event.这个 php 文件将监控浏览器关闭事件。 Once the browser is closed the connection_aborted will return 1 hence the loop will break.一旦浏览器关闭,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调用者.php

This is the file which will call Monitor.php这是将调用 Monitor.php 的文件

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

Parent.html父.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM