KingKerosin
KingKerosin

Reputation: 3841

onbeforeunload not working inside react component

I have a simple react-component where a user can edit data. As the values that may be changed could take some time I want to ask the user to confirm when leaving the page in case of unsaved changes.

In the component's constructor I call:

window.addEventListener("beforeunload", this.handleWindowBeforeUnload);

I also tried

window.onbeforeunload = this.handleWindowBeforeUnload;

The handleWindowBeforeUnload looks like this:

private handleWindowBeforeUnload = (ev: BeforeUnloadEvent): string => {
    return "Unsaved changes. Are you sure?";
}

However, setting a breakpoint will hit. But nevertheless there is no prompt showing that leaving may be dangerous. Also tried with latest Firefox but nothing happened. As stated on MDN I also tried

// Cancel the event as stated by the standard.
e.preventDefault();

// Chrome requires returnValue to be set.
e.returnValue = '';

// return something to trigger a dialog
return null; // ''; // "Do something"

Still nothing happens. What am I doing wrong here?

Upvotes: 6

Views: 25741

Answers (2)

Gibolt
Gibolt

Reputation: 47267

Modern React Solution

useEffect(() => {
  const preventUnload = (event: BeforeUnloadEvent) => {
    // NOTE: This message isn't used in modern browsers, but is required
    const message = 'Sure you want to leave?';
    event.preventDefault();
    event.returnValue = message;
  };

  window.addEventListener('beforeunload', preventUnload);

  return () => {
    window.removeEventListener('beforeunload', preventUnload);
  };
}, []);

You may also need this depending on your lint config:

// eslint-disable-next-line no-param-reassign
event.returnValue = message;

Upvotes: 7

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85583

You'll need to call the method inside the lifecycle methods:

componentDidMount() {
  window.addEventListener("beforeunload", this.handleWindowBeforeUnload);
}

componentWillUnmount() {
  window.removeEventListener("beforeunload", this.handleWindowBeforeUnload);
}

Upvotes: 11

Related Questions