简体   繁体   中英

How to handle browser's window.onbeforeunload event

I want to handle window.onbeforeunload event. I can handle it this way

window.onbeforeunload = function() {
   return "MSG";
}

But in this case it shows a popup asking for user confirmation i dont want that confirmation dialog instead it will directly return false like event.cancel = true .

You cannot do this in the onBeforeUnload. The for this reason is; the user has already sent in a request to move away from the page and the event has been intercepted. The confirm is the best you can do, unless you prevent the event further up the event chain (such as with onkeydown).

For instance, if you want the user to not be able to use their keyboard to go backwards and forwards in history, or to reload the page, this could be achieved using;

var catchKey = { 
    37: true,  /// left
    39: true  /// right
};
window.onkeydown = function(event) {
    if (catchKey[event.keyCode] && event.ctrlKey) {
        event.preventDefault();
        event.stopPropagation();
    }
}

Hope that helps!

Basically you want to prevent the user from closing the browser window/tab or navigate away from your page at all?

I am sure no browser maker will let you do that... then the only way to close the browser in such a case would be to kill the process.

So: Not possible, as far as I can see.

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