Reactjs Browser Tab Close Event

Hi I want to know how to prompt a message on browser tab close. I am using Reactjs.

handleWindowClose(){
    alert("Alerted Browser Close");
},
componentDidMount: function() {
    window.addEventListener('onbeforeunload', this.handleWindowClose);
},

componentWillUnmount: function() {
    window.removeEventListener('onbeforeunload', this.handleWindowClose);
}

this is what I have tried adding to my react component.Please guide me on how to proceed further.


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.


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

I needed to fire logic after the user decided to close the tab. Here is my solution (for functional react components & TypeScript):

useEffect(() => {
    window.addEventListener('beforeunload', alertUser)
    window.addEventListener('unload', handleTabClosing)
    return () => {
        window.removeEventListener('beforeunload', alertUser)
        window.removeEventListener('unload', handleTabClosing)
    }
})

const handleTabClosing = () => {
    removePlayerFromGame()
}

const alertUser = (event:any) => {
    event.preventDefault()
    event.returnValue = ''
}

alertUser warns the user with the default browser dialog. handleTabClosing is fired when the user chooses to close the tab.

I have derived my solution from this blog post from Mike Pottebaum


One can use hooks now to implement the same. e.g.

import { useBeforeunload } from 'react-beforeunload';

and then in your component use:

 useBeforeunload(() => "Are you sure to close this tab?");

Though we are returning custom string, it will show browser's default message here.