When doing web development, we often use the page closing event onbeforeunload, which can give users an opportunity to choose to give up closing, such as this blog editor. If the user chooses to leave, the onunload event will naturally be triggered; but if the user chooses to cancel, how to detect it?
We assume that a page leaves a cancellation event called onunloadcancel. Obviously, this event should fire after the user presses the dialog's Cancel button. But the triggering process for closing the prompt dialog box is not that simple. Let’s review this process first:
When the user is ready to leave the page (such as pressing the close button, or refreshing the page, etc.), the onbeforeunload event is triggered. Our script cannot decide whether to prevent the page from closing in this event. The only thing it can do is to return a string. This string only appears as explanatory text in the close selection dialog box. The user can choose to close or not close. But which one to choose, we have no way of knowing.
However, if we analyze this issue carefully, it is actually not the case. If the user really chooses to close the page, then all running code will be gone byebye; and if the user continues to stay on the page, it will be treated as if nothing has happened, except the onbeforeunload event. Therefore, we do a little trick in the onbeforeunload event and register a timer here that will start after a few milliseconds. If the page is really closed, then of course the timer will be invalid; then the page is still there, and the delay of a few milliseconds will There is no error in this inherently asynchronous interface interaction event.
Sometimes when the close button is pressed, onunloadcancel will also be executed, and a dialog box will flash by. If you change to while(1); the browser will remain stuck, which means that onunloadcancel is indeed executed, but only destroys the interface, but does not pause the running of the script.
If you leave by refreshing the page, onbeforeunload will be executed only once, but if you click the X button to close the page, onbeforeunload will be executed twice. Therefore, we still need to improve it to be compatible with FF.