简体   繁体   English

尝试检测浏览器关闭事件

[英]Trying to detect browser close event

I have tried many methods to detect browser close event through jQuery or JavaScript.我尝试了很多方法来通过 jQuery 或 JavaScript 检测浏览器关闭事件。 But, unfortunately, I have not been able to detect the close.但是,不幸的是,我无法检测到关闭。 The onbeforeunload and onunload methods are also not working. onbeforeunloadonunload方法也不起作用。

How do I detect the window close , unload , or beforeunload events?如何检测窗口closeunloadbeforeunload事件?

Have you tried this code?你试过这个代码吗?

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

$(function () {
    $("a").not('#lnkLogOut').click(function () {
        window.onbeforeunload = null;
    });
    $(".btn").click(function () {
        window.onbeforeunload = null;
});
});

The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.第二个函数是可选的,以避免在单击#lnkLogOut.btn元素时出现提示。

One more thing, The custom Prompt will not work in Firefox (even in latest version also).还有一件事,自定义提示在 Firefox 中不起作用(即使在最新版本中也是如此)。 For more details about it, please go to this thread.有关它的更多详细信息,请转到线程。

Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.参考了各种文章并进行了一些反复试验,最终我开发了这个非常适合我的想法。

The idea was to detect the unload event that is triggered by closing the browser.这个想法是检测关闭浏览器触发的卸载事件。 In that case, the mouse will be out of the window, pointing out at the close button ('X') .在这种情况下,鼠标将移出窗口,指向关闭按钮 ('X')

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
    return "";
}
var prevKey="";
$(document).keydown(function (e) {            
    if (e.key=="F5") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
        window.onbeforeunload = ConfirmLeave;   
    }
    else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
        window.onbeforeunload = ConfirmLeave;
    }
    prevKey = e.key.toUpperCase();
});

The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave() . ConfirmLeave 函数将给出弹出的默认消息,以防需要自定义消息,然后在ConfirmLeave() 函数中返回要显示的文本而不是空字符串。

Try following code works for me under Linux chrome environment.在 Linux chrome 环境下尝试以下代码对我有用。 Before running make sure jquery is attached to the document.在运行之前确保 jquery 附加到文档。

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return confirm("Do you really want to close?"); 
    });
});

For simple follow following steps:对于简单的遵循以下步骤:

  1. open http://jsfiddle.net/打开http://jsfiddle.net/
  2. enter something into html, css or javascript box在 html、css 或 javascript 框中输入内容
  3. try to close tab in chrome尝试在 chrome 中关闭标签

It should show following picture:它应该显示以下图片:

在此处输入图片说明

Hi i got a tricky solution, which works only on new browsers:嗨,我有一个棘手的解决方案,它仅适用于新浏览器:

just open a websocket to your server, when the user closes the window, the onclose event will be fired只需打开一个 websocket 到您的服务器,当用户关闭窗口时,将触发 onclose 事件

Following script will give message on Chrome and IE:以下脚本将在 Chrome 和 IE 上给出消息:

<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here 

    return "Please click 'Stay on this Page' and we will give you candy";
};
</script>

Chrome铬合金
在此处输入图片说明

IE IE
在此处输入图片说明

on Firefox you will get generic message在 Firefox 上,您将收到通用消息

在此处输入图片说明

Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.机制是同步的,所以没有服务器调用延迟会起作用,你仍然可以准备一个像模态窗口这样的机制,如果用户决定留在页面上,但没有办法阻止他离开。

Response to question in comment在评论中回答问题

F5 will fire event again, so will Atl + F4 . F5将再次触发事件, Atl + F4也是如此。

As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,正如 Phoenix 所说,使用 jQuery .bind 方法,但为了更好的浏览器兼容性,您应该返回一个字符串,

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return "Do you really want to close?"; 
    });
});

more details can be found at : developer.mozilla.org可以在以下位置找到更多详细信息: developer.mozilla.org

jQuery .bind() has been deprecated. jQuery .bind()已被弃用。 Use .on() instead使用.on()代替

$(window).on("beforeunload", function() {
    runBeforeClose();
});

Maybe it's better to use the path detecting mouse.也许最好使用路径检测鼠标。

In BrowserClosureNotice you have a demo example and pure javascript library to do it.BrowserClosureNotice 中,您有一个演示示例和纯 javascript 库来完成它。

It isn't perfect, but avoid problems of document or mouse events...它并不完美,但要避免文档或鼠标事件的问题......

<script type="text/javascript">
window.addEventListener("beforeunload", function (e) {

  var confirmationMessage = "Are you sure you want to leave this page without placing the order ?";
  (e || window.event).returnValue = confirmationMessage;
  return confirmationMessage;

});
</script>

Please try this code, this is working fine for me.请试试这个代码,这对我来说很好用。 This custom message is coming into Chrome browser but in Mozilla this message is not showing.此自定义消息已进入 Chrome 浏览器,但在 Mozilla 中未显示此消息。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


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

<script type="text/javascript" language="javascript">

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
  if (!validNavigation) {

            var ref="load";
      $.ajax({
            type: 'get',
            async: false,
            url: 'logout.php',
 data:
            {
                ref:ref               
            },
             success:function(data)
            {
                console.log(data);
            }
            });
     endSession();
  }
 }

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

This is used for when logged in user close the browser or browser tab it will automatically logout the user account...这用于当登录用户关闭浏览器或浏览器选项卡时,它将自动注销用户帐户...

You can try something like this.你可以尝试这样的事情。

<html>
<head>
    <title>test</title>
    <script>
        function openChecking(){
            // alert("open");
            var width = Number(screen.width-(screen.width*0.25));  
            var height = Number(screen.height-(screen.height*0.25));
            var leftscr = Number((screen.width/2)-(width/2)); // center the window
            var topscr = Number((screen.height/2)-(height/2));
            var url = "";
            var title = 'popup';
            var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
            var popup = window.open(url, title, properties);
            var crono = window.setInterval(function() {
                if (popup.closed !== false) { // !== opera compatibility reasons
                    window.clearInterval(crono);
                    checkClosed();
                }
            }, 250); //we check if the window is closed every 1/4 second
        }   
        function checkClosed(){
            alert("closed!!");
            // do something
        }
    </script>    
</head>
<body>
    <button onclick="openChecking()">Click Me</button>
</body>
</html>

When the user closes the window, the callback will be fired.当用户关闭窗口时,将触发回调。

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

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