Search code examples
javascriptgoogle-chromereactjseventsonbeforeunload

How do I prevent double confirmation in chrome with 'onbeforeunload' events in react


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: enter image description here

The problme is that I also get a reload prompt after I choose either option: enter image description here

How do I get rid of the second prompt? What am I doing wrong?


Solution

  • 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
    }