Is there a way to trigger a popup before (or during) the window.beforeunload
confirmation dialog?
I understand that I can't change the contents of the default browser confirmation dialog but let's say I've written a function that shows my own popup. Can I show that either before or during the browser confirmation dialog?
Let's say I have a component:
export MyComponent extends React.Component {
...
componentDidMount() {
window.addEventListener('beforeunload', e => {
triggerPopup()
e.preventDefault()
e.returnValue = ''
return null
})
}
...
}
I put a console statement in my triggerPopup()
function (which shows another React component/modal). It is indeed being called but no popup is shown on the screen. Instead, the default browser confirmation dialog appears and it is only when I click "Cancel" does my popup appear. I would like it to appear before or even at the same time as the default browser dialog. Would it be possible to put a setTimeout
and delay the triggering of the default browser dialog?
Is that possible?
CodePudding user response:
The short answer is: you can't.
The beforeunload
event is treated by browsers with special care because of tons of JavaScript abuse in the past. The only thing you can do is use preventDefault()
to cancel unload without user interaction, or return a message string in returnValue
and let the browser handle interaction. See the docs.
Your custom popup is not actually a popup, but yet another DOM Element inside your page, so it cannot work like a modal popup created natively by the browser. Because of that you might feel tempted to make the event handler function 'wait' somehow for the user interaction with DOM Element (your custom popup) before returning. Can't be done. JavaScript architecture uses an event loop where each message is processed completely before any other message is processed. So if you try to block you event handler and 'wait', the entire page becomes unresponsive.