How can I override the OnBeforeUnload dialog and replace it with my own?

前端 未结 11 2010
一生所求
一生所求 2020-11-21 06:14

I need to warn users about unsaved changes before they leave a page (a pretty common problem).

window.onbeforeunload=handler

This works bu

11条回答
  •  独厮守ぢ
    2020-11-21 07:19

    1) Use onbeforeunload, not onunload.

    2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.

    3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.

提交回复
热议问题