Search code examples
javascriptaddeventlisteneronbeforeunload

Using window.confirm instead of onbeforeunload


Instead of using the onbeforeunload event, is there a way I can listen for when a user tries to refresh the window or close the window, and interrupt that process with my own custom window.confirm message? It seems that onbeforeunload custom messages are no longer supported across browsers.


Solution

  • true that support for onbeforeunload is fading.

    https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

    some browsers ignore the string passed in, and some ignore calls to window.alert(), window.confirm() and window.prompt().

    Many sites get around this by detecting an event that precedes window closure, such as mouseout before the user closes a tab.

    Though it's popular these days, it feels slimy, imo. and it can be triggered when the use is doing another action (perhaps one you want, like "bookmark this page"). Often I see an html5 modal used, which is less offensive than a truly blocking confirm box. It still disrupts reading.