1

I have tried the below code to show alert while we are closing the react application from browser tab, but it not happening, it is closing without alert. I have also tried other helpful posts but nothing worked for me.

Any help would be helpful and appreciated.

    import React from "react";
    import ReactDOM from "react-dom";

    class App extends React.Component {
      onUnload = e => {
        e.preventDefault();
        alert("hi");
      };

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

      render() {
        return "Alok"
      }
    }

    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
Alok Ranjan
  • 967
  • 10
  • 10

1 Answers1

1

Try to create gloabal function handleGloablListeners and handle inside beforeunload event; For example:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  onUnload = (e) => {
    event.returnValue = 'Are you sure you want to leave?';
  };
  componentDidMount() {
    window.addEventListener('beforeunload', this.onUnload);
  }
  render() {
    return "Alok"
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
an_parubets
  • 589
  • 7
  • 15