1

I want to build action before the user close the web tab in Reactjs. This time, I try to use beforeunload but it's not working. How can I try to run it when the web tab is closed.

componentDidMount() {
  window.addEventListener("beforeunload", this.onClose());
}

onClose = () => {
 ...
}

onClose is not working.

k10a
  • 947
  • 2
  • 11
  • 30

1 Answers1

2

this.onClose() in window.addEventListener is actually window.onClose().

Try this:

componentDidMount() {
  const self = this;
  window.addEventListener("beforeunload", self.onClose());
}

Update

It would be a good practice to remove event listener on componentWillUnmount.

Danko
  • 1,819
  • 1
  • 13
  • 12