Skip to content

Instantly share code, notes, and snippets.

@fjahn
Created April 7, 2022 08:15
Show Gist options
  • Save fjahn/91d1411f41d3426a1c517c1d27dc8194 to your computer and use it in GitHub Desktop.
Save fjahn/91d1411f41d3426a1c517c1d27dc8194 to your computer and use it in GitHub Desktop.
Block unload in Browser and Inertia Router using Vue
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()
})
}
<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