Skip to content

Instantly share code, notes, and snippets.

@basarat
Last active October 30, 2018 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save basarat/acb63c0f06fe348c26f754d052dc5fad to your computer and use it in GitHub Desktop.
Save basarat/acb63c0f06fe348c26f754d052dc5fad to your computer and use it in GitHub Desktop.
/** If true is returned it is used to prevent a nav away */
export type Check = () => true | false | undefined;
/** Checks we need to do before leave */
let checks: Check[] = [];
/** Only alert in browsers */
if (typeof window !== 'undefined') {
const getMessageIfAny = () => {
let message: ReturnType<Check> = false;
for (const check of checks) {
message = check();
if (message) break;
}
return message;
}
/** Browser close and reload */
window.addEventListener('beforeunload', (e) => {
const message = getMessageIfAny();
if (!message) return null; // Dont alert
/**
* Note: Browsers no longer allow a custom message
* But you still need to pass a string to trigger the alert
*/
const sampleMessage = 'Changes you made may not be saved.'
e.preventDefault(); // Without this XHRs get cancelled
e.returnValue = sampleMessage; // Gecko, Trident, Chrome 34+
return sampleMessage; // Gecko, WebKit, Chrome <34
});
}
export function alertOnLeave(check: Check) {
checks.push(check);
return () => {
checks = checks.filter(c => c !== check);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment