Created
April 7, 2022 08:15
-
-
Save fjahn/91d1411f41d3426a1c517c1d27dc8194 to your computer and use it in GitHub Desktop.
Block unload in Browser and Inertia Router using Vue
This file contains 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
import { Inertia } from '@inertiajs/inertia' | |
import { onBeforeMount, onBeforeUnmount } from 'vue' | |
/** | |
* @param {() => boolean} shouldBlockUnload | |
* @param {string} message | |
* @returns void | |
*/ | |
export function useBeforeUnload( | |
shouldBlockUnload, | |
message = 'Are you sure you want to leave?' | |
) { | |
function onBeforeUnload(event) { | |
if (shouldBlockUnload()) { | |
event.preventDefault() | |
event.returnValue = message | |
} | |
} | |
function onBefore(event) { | |
if (!shouldBlockUnload()) return | |
const confirmed = confirm(message) | |
if (!confirmed) event.preventDefault() | |
} | |
let removeOnBefore = null | |
onBeforeMount(() => { | |
window.addEventListener('beforeunload', onBeforeUnload) | |
removeOnBefore = Inertia.on('before', onBefore) | |
}) | |
onBeforeUnmount(() => { | |
window.removeEventListener('beforeunload', onBeforeUnload) | |
if (removeOnBefore) removeOnBefore() | |
}) | |
} |
This file contains 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
<template> | |
<input v-model="form.name"> | |
</template> | |
<script setup> | |
const form = useForm({ | |
name: '', | |
}) | |
useBeforeUnload( | |
() => form.isDirty, | |
'You have unsaved changes. Are you sure you want to navigate away?' | |
) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment