简体   繁体   English

jQuery 以编程方式触发 beforeunload 事件

[英]jQuery trigger beforeunload event programmatically

I am trying to invoke browser's onbeforeupload event with jQuery as under:-我正在尝试使用 jQuery 调用浏览器的 onbeforeupload 事件,如下所示:-

<script type="text/javascript">

$(document).ready(function (){
    $(window).trigger('beforeunload');
})

</script>

It doesn't display browser's default onunload event confirm box which means beforeunload event is not getting fired.它不显示浏览器的默认 onunload 事件确认框,这意味着 beforeunload 事件不会被触发。

How can I trigger beforeunload event?如何触发 beforeunload 事件?

Why do you think that showing confirmation dialog is the default behavior?为什么您认为显示确认对话框是默认行为?

The API says: API说:

When this event returns a non-void value, the user is prompted to confirm the page unload.当此事件返回非空值时,系统会提示用户确认页面卸载。 In most browsers, the return value of the event is displayed in this dialog.在大多数浏览器中,事件的返回值显示在此对话框中。 In Firefox 4 and later the returned string is not displayed to the user.在 Firefox 4 及更高版本中,返回的字符串不会显示给用户。 Instead, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved."相反,Firefox 会显示字符串“此页面要求您确认是否要离开 - 您输入的数据可能不会被保存。” See bug 588292.请参阅错误 588292。

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.自 2011 年 5 月 25 日起,HTML5 规范规定在此事件期间可以忽略对 window.alert()、window.confirm() 和 window.prompt() 方法的调用。 See the HTML5 specification for more details.有关更多详细信息,请参阅 HTML5 规范。

Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation).另请注意,各种移动浏览器会忽略事件的结果(即,它们不要求用户确认)。 Firefox has a hidden preference in about:config to do the same. Firefox 在 about:config 中有一个隐藏的偏好来做同样的事情。 In essence this means the user always confirms that the document may be unloaded.本质上,这意味着用户总是确认可以卸载文档。

You can and should handle this event through window.addEventListener() and the beforeunload event.您可以并且应该通过 window.addEventListener() 和 beforeunload 事件处理此事件。 More documentation is available there.那里提供了更多文档。

Because of that, you need to add a handler for the event beforehand:因此,您需要事先为事件添加一个处理程序:

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

Other ways:其他方法:

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

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