Prevent Window From Closing in React.js

Let's say you want to prevent your webpage or the browser from being exited when the user clicks on the Close button, how would you do it in React.js?

We want to put in place an event that triggers a confirmation dialogue asking the user if they "really" want to leave the page. If the user confirms, the browser either navigates to the new page or closes the tab or the browser, depending on the action of the user.

To be clear, this is what we want to put in place.



This syntax below shows how to do it once the page loads in react.js.

 useEffect(() => {
            window.onbeforeunload = confirmExit;
            function confirmExit()
              return "show warning";
    }, [])

You can set it to display after the user triggers an event.

const triggerThis = () => {
        window.onbeforeunload = confirmExit;
        function confirmExit()
          return "show message";

// The button to trigger the action
<button onClick={()=>  triggerThis()}> Click here</button>

The warning message displays if the user clicks on the button first before trying to exit the page or the browser. If the user does not click on the button, the warning message will not display on page exit.

Digging Deeper

The onbeforeunload property of the WindowEventHandlers mixin is the EventHandler for processing beforeunload events. These events fire when a window or a document is about to unload its resources. At this point, the document is still visible and the event can be cancelled.

To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all.

If the onbeforeunload function returns null instead of a string, it will not be displayed on page exit.

For older browsers, you can display a custom message. But that feature has been deprecated in recent browsers.


This feature comes handy on a page that has a form with may fields. The user can be requested to confirm an exit.


Comments (2)

Sandeep Panda's photo

Interesting - thanks for writing this. Please tag it with reactjs instead of react-js for more visibility!

Jed Tony's photo


Thanks for the feedback.