Reactjs Browser Tab Close Event

Amid's answer worked well for me.

The way I used it:

class MyComponent extends Component {
    // Things to do before unloading/closing the tab
    doSomethingBeforeUnload = () => {
        // Do something
    }

    // Setup the `beforeunload` event listener
    setupBeforeUnloadListener = () => {
        window.addEventListener("beforeunload", (ev) => {
            ev.preventDefault();
            return this.doSomethingBeforeUnload();
        });
    };

    componentDidMount() {
        // Activate the event listener
        this.setupBeforeUnloadListener();
    }

    // Render method.
    render() {
        return (
            <div>My component</div>
        )
    }
}

What you did is correct apart from the event name and the fact that alert will be blocked in that particular event.

You can show a message like this:

window.addEventListener("beforeunload", (ev) => 
{  
    ev.preventDefault();
    return ev.returnValue = 'Are you sure you want to close?';
});

Hope this helps.

Tags:

Reactjs