I am trying to trigger a modal when user tries to reload the page, visit new URL or close the browser window/tab.
At the moment, the code is successfully triggering the modal, but a default alert window also pops up which I want to get rid of:
Modal appears below the default alert window (using FireFox)
Code:
componentDidMount() {
window.addEventListener('beforeunload', this.onUnload)
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.onUnload)
}
onUnload(event) {
event.preventDefault();
this.setState({ modalIsOpen: true })
}
There might be a more recommended way to accomplish this, but overriding the alert
function should work:
onUnload(event) {
event.preventDefault();
const nativeAlert = window.alert
window.alert = console.log // Temporarily override the alert function
this.setState({ modalIsOpen: true })
window.alert = nativeAlert // Restore it to default
}
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.