Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 578
KingKerosin Avatar asked Jan 02 '23 20:01

KingKerosin


1 Answers

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

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

componentWillUnmount() {
  window.removeEventListener("beforeunload", this.handleWindowBeforeUnload);
}
like image 85
Bhojendra Rauniyar Avatar answered Jan 07 '23 13:01

Bhojendra Rauniyar