Last active
October 30, 2018 03:05
-
-
Save basarat/acb63c0f06fe348c26f754d052dc5fad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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