简体   繁体   English

beforeunload 在页面刷新和 href 点击时被调用

[英]beforeunload getting called on page refresh and href clicks

I am using the following function to detect browser close, or someone types some other website name etc,我正在使用以下 function 来检测浏览器关闭,或者有人键入其他网站名称等,

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

But the above code is getting called for page refresh, href clicks, form submits etc但是上面的代码被调用以进行页面刷新、href 点击、表单提交等

how can retrict not to run the above code in these scenarios, or am i missing some other method在这些情况下如何限制不运行上述代码,或者我错过了其他一些方法

any help or pointers to code will be appreciated任何帮助或代码指针将不胜感激

beforeunload gets called before the current page is being unloaded no matter where the next destination is - any other page, even on your own site,even a reload of the current URL. beforeunload 在当前页面被卸载之前被调用,无论下一个目的地在哪里 - 任何其他页面,即使在您自己的站点上,甚至是当前 URL 的重新加载。 The idea behind the function is to be able to ask the user about unsaved data in this particular web page so it's triggered when anything that might cause that data to be lost is about to happen. function 背后的想法是能够向用户询问此特定 web 页面中未保存的数据,以便在可能导致该数据丢失的任何事情即将发生时触发。

According to the mozilla docs , there is no standard for this method.根据mozilla 文档,这种方法没有标准。 It was implemented by IE4 and copied by other browsers.它由IE4实现并被其他浏览器复制。

I don't see any way to know why the page is about to be closed.我看不到任何方法可以知道为什么该页面即将关闭。 Usually, the way this is used is that the page keeps track of some sort of changeflag and only prompts the user if they have important, unsaved data.通常,这种使用方式是页面跟踪某种更改标志,并且仅在用户有重要的、未保存的数据时才提示用户。

Here's Microsoft's documentation on the event data that comes this event.这是Microsoft 关于此事件附带的事件数据的文档 You will have to devise some tests to see if you can reliably tell (across browsers) what is causing this to get called and avoid your prompt in some cases.您将不得不对 devise 进行一些测试,看看您是否可以可靠地告诉(跨浏览器)是什么导致它被调用并在某些情况下避免您的提示。

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

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