简体   繁体   中英

jQuery trigger beforeunload event programmatically

I am trying to invoke browser's onbeforeupload event with jQuery as under:-

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

How can I trigger beforeunload event?

Why do you think that showing confirmation dialog is the default behavior?

The API says:

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.

Because of that, you need to add a handler for the event beforehand:

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

Other ways:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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