Share JavaScript to get page closed and unclosed events

  • 2020-03-30 00:52:17
  • OfStack

When doing Web development, we often use the page close event onbeforeunload to give users a chance to opt out of closing, like this blog editor. If the user chooses to leave, the onunload event will naturally be triggered. But if the user chooses to cancel, how do you detect it?

We assume that a page leaves the cancel event, called onunloadcancel. Obviously, this event should trigger after the user presses the cancel button on the dialog box. But closing the triggering process for the prompt dialog is not that simple. Let's review the process:


window.onbeforeunload = function()
{
    return " Really leave ?";
}

When the user is ready to leave the page (such as pressing the close button, or refreshing the page, etc.), the onbeforeunload event fires. Our script cannot decide in this event whether to prevent the page from closing, the only thing it can do is to return a string that appears only as a caption in the close selection dialog box, and the user can choose to close it or not. But we don't know which one.

But look closely at the problem, and it's not. If the user does choose to close the page, then all the running code is byebye. While remaining on the page, assume that nothing has ever happened, except for the onbeforeunload event. So, we did a little trick in the onbeforeunload event, where we registered a timer that started a few milliseconds later. The page is still there, and the delay of a few milliseconds has no error for this otherwise asynchronous interface interaction event.


<script language="JavaScript">
window.onbeforeunload = function()
{
    setTimeout(onunloadcancel, 10);
    return " Really leave ?";
}
window.onunloadcancel = function()
{
    alert(" Cancel the leave ");
}
</script>

We execute the onunloadcancel with a delay of 10ms using setTimeout. If the page does close, of course the timer is destroyed; And vice versa. During testing, however, two bugs were found in FireFox:

Sometimes when the close button is pressed, the onunloadcancel is also performed, and a dialog box flashes by. If I replace it with while(1); The browser will remain stuck, which means that the onunloadcancel is actually executed, only the interface is destroyed, but the script is not paused.
If you are leaving by refreshing the page, onbeforeunload is performed only once, but clicking the X button to close the page will perform onbeforeunload twice. Therefore, we still need to improve in order to be compatible with FF.


<script language="JavaScript">
var _t;
window.onbeforeunload = function()
{
    setTimeout(function(){_t = setTimeout(onunloadcancel, 0)}, 0);
    return " Really leave ?";
}
window.onunloadcancel = function()
{
    clearTimeout(_t);
    alert(" Cancel the leave ");
}
</script>

Here I use a method that I can't say why, which should be considered a hack to solve the bug under FF.


Related articles: