简体   繁体   中英

onunload not working in combination with onbeforeunload in Safari

I want to make sure the user gets a warning when closing the window on some occasions (unsaved data, for example). Works well.

BUT: I also need to do some clean up work BEFORE the window closes but AFTER I asked whether the user really wants to close it.

So I have two callback functions, one for onbeforeunload that will throw the confirmation dialog, and one for onunload that should do the cleanup.

Unfortunately, in Safari, the onunload callback does not seem to be called.

Why?

$(window).on('beforeunload',function() {
    if (connected)
        return "Are you sure you want to close the window!";
});

$(window).on('unload',function() {
    localStorage.removeItem("someItem"); // never executed in Safari
});

Unfortunately, this event is not supported in some of the browsers. You can try using pagehide event instead of onunload.

Good Luck!

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