How To Create A Simple Alert For An onbeforeunload Event (Closing Browser or Navigating Away From Page) [updated]

Tia Eastwood - May 11 '21 - - Dev Community

edit: credit to Alex Lohr for suggesting to put the code inside a useEffect :)

Here is a useful little snippet for if you have a page like a checkout or a survey and you want to warn people about leaving the page before they've completed it.



  window.onbeforeunload = (event) => {
    if (whatever your condition is here) {
      return true;
    }
  };


// inside a useEffect:
useEffect(() => {
  if (conditionState) {
    const listener = () => true
    window.addEventListener('beforeunload', listener)
    return () => window.removeEventListener('beforeunload', listener)
  }
}, [conditionState])


// the return here removes the eventListener, until next time the useEffect runs again 


Enter fullscreen mode Exit fullscreen mode

The alert gives the user the option to confirm or cancel their navigation. Alerts should never stop someone from leaving a page or closing their browser though; that's a big no-no.

An example of a browser alert

An onbeforeunload event occurs when the document (the current page of your site/application) is about to be unloaded (closed/exited). A example of this would be someone closing the browser window or clicking a link to a different page.

Most browsers will show a default message like "changes you've made will not be saved". You can't edit this message, but it does the job as a warning. Due to this, you don't need to return any specific content or message in the function, just return true in order for it to work.

This function will be called when an onbeforeunload event occurs. If the condition inside is met, then the function will return true and the alert will be shown. So all you need to do is apply a condition to decide when the alert will be shown. For example, if using this in a React application, then the condition could be based on a certain state.

There are other ways of achieving this sort of behaviour, such as using Prompt in react-router, but if you're just looking for a simple solution then I hope this helps! If you have anything to add, please leave a comment.

. . . . . . . . . . . . . . . . . . . . . .