简体   繁体   中英

Is there any way to handle the browser/tab close other than beforeunload or onbeforeunload or unload

Is there any way to handle the browser/tab close other than beforeunload or onbeforeunload or unload. because I tried all the 3 events but the default pop up is coming. I don't want that default pop up but I want do something on the close click.

You can't outright block the closure of a window/tab with preventDefault or any other method. Because of this limitation, you can't use a custom modal, etc. to show a message. Your only option is to return a message, which can be bypassed.

window.onbeforeunload = function(){
    return "Do you want to leave?";
}

(Demo: http://jsfiddle.net/9sAE4/embedded/result/ )

Note that Firefox does not presently show the user the included message, but rather a generic message asking if the user wishes to leave.

No. The only way to do anything when the window is closed is to use onbeforeunload , and the things you're allowed to do are quite limited. Firefox and Chrome prevent your using alert or confirm , for instance (but do support returning a string from the handler, which then they'll use to show the user the choice to stay on the page). Some browsers may allow synchronous ajax calls, but I don't think all do, and I'd avoid it if I were you. You can probably set items in local storage.

From your comment:

I dont want to close the browser/tab and I want to show my own Pop up

You can't. All you can do is hook onbeforeunload and return a string , which the browser will use to offer the user a chance to stay on the page. You can't style that window, or control it.

window.onbeforeunload = function() {
    return "Your message here.";
};

Example

Note that recent versions of Firefox don't even show your message, they just use a generic "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (or similar) instead.

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