Skip to content

Instantly share code, notes, and snippets.

@Hfreitas
Created April 29, 2021 17:49
Show Gist options
  • Save Hfreitas/c962e46627c3d160291c613c0c1adb8c to your computer and use it in GitHub Desktop.
Save Hfreitas/c962e46627c3d160291c613c0c1adb8c to your computer and use it in GitHub Desktop.
export default (when = false): void => {
const onUnload = (event: BeforeUnloadEvent): string => {
// garantindo compatibilidade com browser antigos e mobile
const listener = event || window.event;
listener.preventDefault();
if (listener) {
/* compatibilidade com browser engines Gecko (Firefox),
Trident(Internet Explorer) e Chrome versões 34+ */
listener.returnValue = '';
}
/* compatibilidade com browser engines Gecko (Firefox) versões anteriores
a 4, Webkit(browsers iOS, Safari, Chrome <= 27) e Chrome versões <34 */
return '';
};
useEffect(() => {
if (!when) return undefined;
window.addEventListener('beforeunload', onUnload);
return () => {
window.removeEventListener('beforeunload', onUnload);
};
}, [when]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment