Reactjs Browser Tab Close Event

Reactjs

Reactjs Problem Overview


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.

Reactjs Solutions


Solution 1 - Reactjs

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.

Solution 2 - Reactjs

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

Solution 3 - Reactjs

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

Solution 4 - Reactjs

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.

Solution 5 - Reactjs

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

Solution 6 - Reactjs

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondhrDattView Question on Stackoverflow
Solution 1 - ReactjsAmidView Answer on Stackoverflow
Solution 2 - ReactjsArtur BarseghyanView Answer on Stackoverflow
Solution 3 - ReactjsHannes SchaletzkyView Answer on Stackoverflow
Solution 4 - ReactjsJyoti DuhanView Answer on Stackoverflow
Solution 5 - ReactjsDrew ReeseView Answer on Stackoverflow
Solution 6 - ReactjsMD SHAYONView Answer on Stackoverflow