jQuery 以编程方式触发 beforeunload 事件

jQuery trigger beforeunload event programmatically

我正在尝试使用 jQuery 调用浏览器的 onbeforeupload 事件,如下所示:-

<script type="text/javascript">

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

</script>

它不显示浏览器默认的 onunload 事件确认框,这意味着 beforeunload 事件没有被触发。

如何触发 beforeunload 事件?

为什么您认为显示确认对话框是默认行为?

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. 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." See bug 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. See the HTML5 specification for more details.

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. 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. More documentation is available there.

因此,您需要预先为事件添加处理程序:

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

其他方式:

  • Is it possible to trigger the onbeforeunload event programmatically?