Reputation: 7324
I want to prompt people to confirm before they leave a page.
I added and event listener in componentDidMount:
componentDidMount() {
window.addEventListener('beforeunload', this.onUnload)
}
Then I wrote the event I want to happen:
onUnload(e) {
var message = "Random message to trigger the browser's native alert."
e.returnValue = message
return message
}
Then I bound the event in the constructor:
constructor(props) {
super(props)
this.onUnload = this.onUnload.bind(this)
}
And finally I removed the event listener on unmount:
componentWillUnmount() {
window.removeEventListener('beforeunload', this.onUnload)
}
Everything seems to work fine. I get the following prompt when I try and close the tab in chrome:
The problme is that I also get a reload prompt after I choose either option:
How do I get rid of the second prompt? What am I doing wrong?
Upvotes: 1
Views: 2014
Reputation: 1198
You can move window.removeEventListener
to the onUnmount
method to ensure it gets called. So something like this should work:
onUnload(e) {
window.removeEventListener('beforeunload', this.onUnload)
var message = "Random message to trigger the browser's native alert."
e.returnValue = message
return message
}
Upvotes: 1