【问题标题】:Trying to detect browser close event试图检测浏览器关闭事件
【发布时间】:2014-01-18 03:23:52
【问题描述】:

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

如何检测窗口closeunloadbeforeunload 事件?

【问题讨论】:

  • 我不想关闭浏览器,我想检测关闭事件。我试过的是 window.onbeforeunload = function (e) { var message = "你的确认信息在这里。", e = e ||窗口.事件; // 对于 IE 和 Firefox if (e) { e.returnValue = message; } // 对于 Safari 返回消息; };
  • “关闭”是指完全退出浏览器应用程序还是只是关闭选项卡或窗口?当然,关闭最后打开的选项卡或窗口可能是相同的,具体取决于浏览器。但是,弄清楚您的意思仍然会有所帮助。
  • $(window).unload(function(){var e=confirm("Are you sure you want to exit?");if(e){}})
  • 您无法检测到浏览器的关闭,只能检测到当前文档的关闭。
  • Browser window close event 的可能重复项

标签: javascript jquery browser


【解决方案1】:

你试过这个代码吗?

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 线程。

【讨论】:

  • @Ravi 代码很好。但是,如果用户单击“离开此页面”,我想触发注销功能。但是如何检测用户是否点击了“离开此页面”?
  • 我不确定这是否可能。据我所知,这是不可能的。但是,您能否发布一个新问题并参考此答案,以便社区会说什么。
  • @Bit_hunter,您可以执行一个函数,在其中显示自定义 div,用户可以按是或否
  • 有没有办法避免页面刷新时出现提示信息?
  • 自定义消息不显示,只显示浏览器默认消息
【解决方案2】:

参考了各种文章并进行了一些反复试验,最后我提出了这个非常适合我的想法。

这个想法是检测关闭浏览器触发的卸载事件。在这种情况下,鼠标将离开窗口,指向关闭按钮 ('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 函数会给出弹出的默认消息,如果需要自定义消息,则返回要显示的文本,而不是 function ConfirmLeave() 中的空字符串。

【讨论】:

  • 当用户按下离开页面按钮时启动 ajax 怎么样?如果不是那么可以替代它
  • 我最喜欢的答案。这样可以避免列出所有可能导致您离开页面的 DOM 元素。除此之外,该代码还检测标签\窗口关闭键盘快捷键。
  • 嗨希夫。对于大多数情况,这似乎工作正常,除了 ALT+F4 没有其他选项卡时,即在浏览器中打开页面并按 Alt + F4。这将关闭浏览器而不显示消息。 Ctrl + F4 在相同的情况下工作。有什么想法吗?
  • 此外,如果您单击浏览器后退或前进,因为鼠标不在该按钮的窗口中,它会触发。 :-(
  • 解决方案很好,但是,在我的情况下,它似乎只有在开发人员的控制台在浏览器中打开时才有效。如果我点击页面(焦点在页面上),那么它不起作用。任何想法,为什么会这样?
【解决方案3】:

尝试以下代码在 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 中关闭标签

它应该显示以下图片:

【讨论】:

  • 对不起,在ubuntu我没有Mozilla 33。所以你可以查一下jsfiddle的实现
  • 小提琴网址不再起作用。请检查并更新
  • @ShashankVivek 小提琴链接确实有效。再次阅读答案。他们从当前版本的 web ui 中删除了“beforeunload”事件处理。因此,您将不会再在 jsfiddle 中看到通知窗口。但是使用脚本上部您仍然可以自己处理事件。我无能为力。
  • 在卸载前被阻止确认('你真的要关闭吗?')。
  • 目前工作于 2021 年,改为 on 而不是 bind。但我确实有一个问题。当用户点击离开时我们可以运行一个函数吗??
【解决方案4】:

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

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

【讨论】:

  • 嗨,我们可以在这个 onclose 事件上显示一个模式窗口/自定义弹出窗口吗?
  • @JyotiDuhan 不,你只能在服务器端检测到它
  • 对于页面刷新太onclose会被调用
【解决方案5】:

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

在 Firefox 上,您将收到一般消息

机制是同步的,因此服务器调用延迟不会起作用,您仍然可以准备一个机制,例如当用户决定留在页面上时显示的模式窗口,但无法阻止他离开。

回复评论中的问题

F5 将再次触发事件,Atl+F4 也是如此。

【讨论】:

  • 我只想在用户关闭选项卡或导航器和 Alt+F4 时检测。
  • @Kiquenet 我刚刚在 IE8 上测试了 Alt + f4 并且它确实触发了机制,我在测试 Crome 时一定做错了它在所有浏览器(IE、Chrome、Firefox)上触发
  • 当用户按下离开页面按钮时启动 ajax 怎么样?如果不是那么可以替代它
  • 有没有办法避免页面刷新时的提示信息?
  • 我正在寻找检测 HTA 应用程序的关闭事件,这个解决方案非常有效。
【解决方案6】:

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

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

更多详情请访问:developer.mozilla.org

【讨论】:

    【解决方案7】:

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

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

    【讨论】:

      【解决方案8】:

      也许用路径检测鼠标会更好。

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

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

      【讨论】:

      • 如果用户只是将鼠标悬停在关闭按钮上,但从不按下怎么办?以及如何处理移动浏览器上的情况?
      • 此代码检测鼠标何时移至关闭按钮,但不检测何时按下关闭按钮。如果你愿意,你也可以添加这个事件。就我而言,我不想避免关闭,如果我认为您正在考虑关闭页面,我想显示信息。
      • 但这在移动浏览器上无论如何都行不通,所以解决办法不是鸡蛋里的黄色。
      • 当然,这种方法不是移动浏览器的解决方案
      【解决方案9】:
      <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 中未显示此消息。

      【讨论】:

        【解决方案10】:
        <!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> 
        

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

        【讨论】:

        • 请解释一下为什么这样做以及它是如何工作的
        • 这用于当登录用户关闭浏览器或浏览器选项卡时,它将自动注销用户帐户..并在数据库中进行更改.....
        【解决方案11】:

        你可以试试这样的。

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

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

        【讨论】:

          猜你喜欢
          • 2015-04-11
          • 1970-01-01
          • 2011-08-13
          • 2021-12-23
          • 1970-01-01
          相关资源
          最近更新 更多