There’s a specific function for this: beforeunload
.
Adapt beforeunload to React, we get:
class Prompt extends React.Component {
componentDidMount() {
window.addEventListener('beforeunload', this.beforeunload.bind(this));
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.beforeunload.bind(this));
}
beforeunload(e) {
if (this.props.dataUnsaved) {
e.preventDefault();
e.returnValue = true;
}
}
render() {...}
}
Also, the thing to keep in mind is that it is not possible to customize the content of the message, due to security reasons. So different browsers will display a pre-designed sentence, e.g.,
- Firefox displays the string, “This page is asking you to confirm that you want to leave – data you have entered may not be saved.”
- Chrome displays the string, “Do you want to leave this site? Changes you made may not be saved.”
If you write the beforeunload method like this:
beforeunload = (e) => {
if (this.props.dataUnsaved) {
e.preventDefault();
e.returnValue = true;
}
};
you can write
window.addEventListener(‘beforeunload’, this.beforeunload);
and
window.removeEventListener(‘beforeunload’, this.beforeunload);
Pingback: Jak powiadomić użytkownika o niezapisanych zmianach? - Ach te Internety