Created
January 30, 2017 07:47
-
-
Save basarat/6ca157b24dd9cb4961b00315084ae8f6 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
export interface Check { | |
/** If a message is returned it is used to prevent a nav away */ | |
(): string | null | undefined; | |
} | |
/** Checks we need to do before leave */ | |
let checks: Check[] = []; | |
/** Only alert in browsers */ | |
if (typeof window !== 'undefined') { | |
const getMessageIfAny = () => { | |
let message = ''; | |
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; // Dont alert | |
e.preventDefault(); // Without this XHRs get cancelled | |
e.returnValue = message; // Gecko, Trident, Chrome 34+ | |
return message; // 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