How to prevent JavaScript alerts that fire when leaving a page?

Solution 1:

Well, the simplest thing to do is simply override the pages script directly, and reassign the event to null.

window.onbeforeunload = null;

This should work anywhere, unless they are truly malicious, and keep reassigning it themselves. In such a case, a loop to keep setting null will probably work.

while(true) {
    if (window.onbeforeunload != null) {
        window.onbeforeunload = null;
    }
}

Now, be warned, some pages use this for good. Take the YouTube upload page: If you navigate away during an upload, you may have lost hours of progress! Or perhaps a web form you are filling out, which you may not want to fill out again, or a message (forum/email) that you may not want to retype. With this feature, you are protected.

Another issue is any page using this for some secondary purpose, like saving data by AJAX. They may use this event to trigger the save action, and hope that the user takes long enough to click the button for the request to go through. Again, this is often done to save you from yourself.

But, obviously, we all know many pages use this for ill. So if you know of any pages you want it working on, you could always have a white list system. There really isn't a way to block this action, without totally blocking window.onbeforeunload, and any (possibly good) actions it may take.

There is no way (without prior knowledge of a given pages code) to keep the good actions while stopping the popup box. This box is not an alert(). The box is generated by the browser, as the intended behavior of onbeforeunload. One creates it by making whatever function they assign to window.onbeforeunload return a string. That string will be printed in the popup.

window.onbeforeunload = function() {
    //Whatever
    return "WARNING! You have unsaved changes that may be lost!";
}

Thus, you would be unable to block the popup without erasing the function.

Plus, if you did find a way, any AJAX would fail. The popup gives requests time to go through, without it, data may be lost.

As for onunload, it should not be possible to block you with this. Since it fires after the page unloads. But to be safe, you can always do a window.onunload = null; and it should be taken care of.