通过 jQuery 检测关闭窗口事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16707249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:37:48  来源:igfitidea点击:

Detect Close windows event by jQuery

javascriptjqueryjquery-events

提问by Duc Le

Could you please give me the best way to detect only window close eventfor all browsersby jQuery?

能否请您给我检测的最好方法只有窗口关闭事件所有的浏览器的jQuery?

I mean clicking Xbutton on the browser or window.close(), not meaning F5, form submission, window.locationor link. I was looking for many threads but have not found the right way yet.

我的意思是单击X浏览器上的按钮 或window.close(),而不是F5表单提交 window.location或链接。我一直在寻找许多线程,但还没有找到正确的方法。

采纳答案by Naveenkumar K

There is no specific event for capturing browser close event.

没有用于捕获浏览器关闭事件的特定事件。

You can only capture on unload of the current page.

您只能在卸载当前页面时捕获。

By this method, it will be effected while refreshing / navigating the current page.

通过这种方法,它会在刷新/导航当前页面时生效。

Even calculating of X Y postion of the mouse event doesn't give you good result.

即使计算鼠标事件的 XY 位置也不会给您带来好的结果。

回答by mjimcua

You can use:

您可以使用:

$(window).unload(function() {
    //do something
}

Unload() is deprecated in jQuery version 1.8, so if you use jQuery > 1.8 you can use even beforeunload instead.

Unload() 在 jQuery 1.8 版中已弃用,因此如果您使用 jQuery > 1.8,您甚至可以使用 beforeunload 代替。

The beforeunload event fires whenever the user leaves your page for any reason.

每当用户出于任何原因离开您的页面时,都会触发 beforeunload 事件。

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

Source Browser window close event

浏览器窗口关闭事件

回答by Rahul Vyas

The unload() method was deprecated in jQuery version 1.8.

unload() 方法在 jQuery 1.8 版中已弃用。

so if you are using versions older than 1.8

所以如果你使用的版本早于 1.8

then use -

然后使用 -

$(window).unload(function(){
alert("Goodbye!");
});

and if you are using 1.8 and higher

如果您使用的是 1.8 及更高版本

then use -

然后使用 -

window.onbeforeunload = function() {
    return "Bye now!";
};

hope this will work :-)

希望这会奏效:-)

回答by user3559718

There is no specific event for capturing browser close event. But we can detect by the browser positions XY.

没有用于捕获浏览器关闭事件的特定事件。但是我们可以通过浏览器位置 XY 来检测。

<script type="text/javascript">
$(document).ready(function() {
  $(document).mousemove(function(e) {
    if(e.pageY <= 5)
    {
        //this condition would occur when the user brings their cursor on address bar 
        //do something here 
    }
  });
});
</script>

回答by Harris Yer

Combine the mousemove and window.onbeforeunload event :-I used for set TimeOut for Audit Table.

结合 mousemove 和 window.onbeforeunload 事件:-我用于为审计表设置超时。

 $(document).ready(function () {
 var checkCloseX = 0;
        $(document).mousemove(function (e) {
            if (e.pageY <= 5) {
                checkCloseX = 1;
            }
            else { checkCloseX = 0; }
        });

        window.onbeforeunload = function (event) {
            if (event) {
                if (checkCloseX == 1) {

                    //alert('1111');
                    $.ajax({
                        type: "GET",
                        url: "Account/SetAuditHeaderTimeOut",
                        dataType: "json",
                        success: function (result) {
                            if (result != null) {
                            }
                        }
                    });
                }
            }
        };
  });

回答by tuanngocptn

You can solve this problem with vanilla-Js:

你可以用 vanilla-Js 解决这个问题:

Unload Basics

卸载基础知识

If you want to prompt or warn your user that they're going to close your page, you need to add code that sets .returnValueon a beforeunloadevent:

如果你想提示或警告用户,他们打算关闭您的网页,你需要添加代码,设置.returnValue一个beforeunload事件:

    window.addEventListener('beforeunload', (event) => {
      event.returnValue = `Are you sure you want to leave?`;
    });

There's two things to remember.

有两件事要记住。

  1. Most modern browsers (Chrome 51+, Safari 9.1+ etc) will ignore what you say and just present a generic message. This prevents webpage authors from writing egregious messages, e.g., "Closing this tab will make your computer EXPLODE! ".

  2. Showing a prompt isn't guaranteed. Just like playing audio on the web, browsers can ignore your request if a user hasn't interacted with your page. As a user, imagine opening and closing a tab that you never switch to—the background tab should notbe able to prompt you that it's closing.

  1. 大多数现代浏览器(Chrome 51+、Safari 9.1+ 等)会忽略您所说的内容,只显示一般性消息。这可以防止网页作者编写令人震惊的消息,例如,“关闭此选项卡将使您的计算机爆炸!”。

  2. 不能保证显示提示。就像在网络上播放音频一样,如果用户没有与您的页面进行交互,浏览器可以忽略您的请求。作为用户,想象一下打开和关闭一个你从未切换到的选项卡——背景选项卡应该提示你它正在关闭。

Optionally Show

可选显示

You can add a simple condition to control whether to prompt your user by checking something within the event handler. This is fairly basic good practice, and could work well if you're just trying to warn a user that they've not finished filling out a single static form. For example:

您可以添加一个简单的条件,通过检查事件处理程序中的某些内容来控制是否提示您的用户。这是相当基本的良好实践,如果您只是想警告用户他们尚未完成单个静态表单的填写,则可能会很好地工作。例如:

    let formChanged = false;
    myForm.addEventListener('change', () => formChanged = true);
    window.addEventListener('beforeunload', (event) => {
      if (formChanged) {
        event.returnValue = 'You have unfinished changes!';
      }
    });

But if your webpage or webapp is reasonably complex, these kinds of checks can get unwieldy. Sure, you can add more and more checks, but a good abstraction layer can help you and have other benefits—which I'll get to later. ?♀?

但是如果您的网页或 web 应用程序相当复杂,这些类型的检查可能会变得笨拙。当然,您可以添加越来越多的检查,但是一个好的抽象层可以帮助您并带来其他好处——我将在后面介绍。?♀?



Promises

承诺

So, let's build an abstraction layer around the Promiseobject, which represents the future resultof work- like a response from a network fetch().

所以,让我们围绕Promise对象构建一个抽象层,它代表工作的未来结果——就像来自网络的响应一样fetch()

The traditional way folks are taught promises is to think of them as a single operation, perhaps requiring several steps- fetch from the server, update the DOM, save to a database. However, by sharing the Promise, other code can leverage it to watch when it's finished.

人们学习 Promise 的传统方式是将它们视为单个操作,可能需要几个步骤——从服务器获取、更新 DOM、保存到数据库。但是,通过共享Promise,其他代码可以利用它来查看它何时完成。

Pending Work

待处理的工作

Here's an example of keeping track of pending work. By calling addToPendingWorkwith a Promise—for example, one returned from fetch()—we'll control whether to warn the user that they're going to unload your page.

这是跟踪待处理工作的示例。通过调用- 例如,从 - 返回的addToPendingWork一个Promise- 我们将fetch()控制是否警告用户他们将要卸载您的页面。

    const pendingOps = new Set();

    window.addEventListener('beforeunload', (event) => {
      if (pendingOps.size) {
        event.returnValue = 'There is pending work. Sure you want to leave?';
      }
    });

    function addToPendingWork(promise) {
      pendingOps.add(promise);
      const cleanup = () => pendingOps.delete(promise);
      promise.then(cleanup).catch(cleanup);
    }

Now, all you need to do is call addToPendingWork(p)on a promise, maybe one returned from fetch(). This works well for network operations and such- they naturally return a Promisebecause you're blocked on something outside the webpage's control.

现在,您需要做的就是调用addToPendingWork(p)一个 promise,也许是从fetch(). 这适用于网络操作等 - 它们自然会返回 aPromise因为您被网页控制之外的某些内容阻止。

more detail can view in this url:

更多细节可以在这个网址查看:

https://dev.to/chromiumdev/sure-you-want-to-leavebrowser-beforeunload-event-4eg5

https://dev.to/chromiumdev/sure-you-want-to-leavebrowser-beforeunload-event-4eg5

Hope that can solve your problem.

希望能解决你的问题。