Prompt for unsaved change for JavaScript or React application

import { withRouter } from 'react-router'; promptUnsavedChange(isUnsaved = false, leaveMessage = 'Leave with unsaved change?') { // Detecting page transition (prevent leaving by setting true) // for React Router version > 2.4 this.props.router.setRouteLeaveHook(this.props.route, () => isUnsaved && confirm(leaveMessage)); // Detecting browser close window.onbeforeunload = isUnsaved && (() => leaveMessage); } componentDidUpdate() { this.promptUnsavedChange(this.isDirty()); } componentWillUnmount() { window.onbeforeunload = null; } export default withRouter(YourComponent);
In React application, it is needed to check against page transition via React Router API since it is not a pure redirect which will not trigger onbeforeunload event.

In pure JavaScript application, you just need to assign callback function to window.onbeforeunload.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.