试图检测浏览器关闭事件

时间:2013-12-31 06:49:40

标签: javascript jquery browser

我尝试了很多通过jQuery或JavaScript检测浏览器关闭事件的方法。但是,不幸的是,我无法发现关闭。 onbeforeunloadonunload方法也无效。

如何检测窗口closeunloadbeforeunload事件?

11 个答案:

答案 0 :(得分:61)

您是否尝试过此代码?

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;
});
});

第二个功能是可选的,以避免在点击#lnkLogOut.btn元素时提示。

还有一件事,自定义提示在Firefox中不起作用(即使在最新版本中也是如此)。有关它的更多详细信息,请转到this主题。

答案 1 :(得分:37)

参考各种文章并进行一些试验和错误测试,最后我发展了这个适合我的想法。

想法是检测通过关闭浏览器触发的卸载事件。在这种情况下,鼠标将离开窗口,指向关闭按钮('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();
});

ConfirmLeave函数将提供弹出的默认消息,以防需要自定义消息,然后在函数ConfirmLeave()中返回要显示的文本而不是空字符串。

答案 2 :(得分:11)

在Linux Chrome环境下尝试使用以下代码。在运行之前,请确保将jquery附加到文档中。

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

简单按照以下步骤操作:

  1. 打开http://jsfiddle.net/
  2. 在html,css或javascript框中输入内容
  3. 尝试关闭Chrome中的标签
  4. 应该显示以下图片:

    enter image description here

答案 3 :(得分:7)

您好我有一个棘手的解决方案,它仅适用于新的浏览器:

只需打开一个websocket到你的服务器,当用户关闭窗口时,onclose事件将被触发

答案 4 :(得分:3)

以下脚本将在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>


enter image description here

IE
enter image description here

在Firefox上

您将获得通用消息

enter image description here

机制是同步的,所以没有服务器调用延迟工作,你仍然可以准备一个机制,如模式窗口,如果用户决定留在页面上显示,但无法阻止他离开。

回复评论中的问题

F5 将再次触发事件,因此 Atl + F4

答案 5 :(得分:3)

正如凤凰城所说,使用jQuery .bind方法,但为了更多的浏览器兼容性,你应该返回一个字符串,

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

更多详细信息,请访问:developer.mozilla.org

答案 6 :(得分:0)

使用路径检测鼠标可能更好。

BrowserClosureNotice中,您有一个演示示例和纯javascript库来执行此操作。

这不完美,但避免文档或鼠标事件的问题...

答案 7 :(得分:0)

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

请尝试使用此代码,这对我来说很好。此自定义消息即将进入Chrome浏览器,但在Mozilla中此消息未显示。

答案 8 :(得分:0)

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

这用于登录用户关闭浏览器或浏览器选项卡时会自动注销用户帐户...

答案 9 :(得分:0)

jQuery .bind()已被弃用。请改用.on()

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

答案 10 :(得分:-2)

你可以尝试这样的事情。

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

当用户关闭窗口时,将触发回调。