score:77

Accepted answer

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.

score:1

You can show on unmounting component but you can't show a custom message on window close. Modern browser doesn't support it (Check browser compatibility). You can set an alert on a click event and there you can set some custom message.

Thank you

score:4

If you want to display a sort of confirmation before leaving the page then follow the beforeunload event guidelines:

According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event.

However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods:

  • assigning a string to the event's returnValue property
  • returning a string from the event handler.

To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.

The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML specification for more details.

This should cover most cases. Use a mounting useEffect to define the callback, add the event listener, and return the cleanup function to remove the listener.

useEffect(() => {
  const unloadCallback = (event) => {
    event.preventDefault();
    event.returnValue = "";
    return "";
  };

  window.addEventListener("beforeunload", unloadCallback);
  return () => window.removeEventListener("beforeunload", unloadCallback);
}, []);

enter image description here enter image description here

Edit put-a-warning-if-page-refresh-in-reactjs

score:9

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.

score:13

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

score:26

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

Related Query

More Query from same tag