We can use the native beforeunload
event to detect when a user is about to navigate away or refresh the page:
// Use `beforeMount` to avoid running during SSRonBeforeMount(() => {// We use the native `beforeunload` eventwindow.addEventListener("beforeunload", preventNav);});// Make sure to always clean up after yourself!onBeforeUnmount(() => {window.removeEventListener("beforeunload", preventNav);});
The method to actually block the navigation uses preventDefault
:
const blockNavigation = ref(false);const preventNav = event => {if (!blockNavigation.value) return;event.preventDefault();// Chrome requires returnValue to be setevent.returnValue = "";};
Here's the full example:
<script setup>import { ref, onBeforeMount, onBeforeUnmount } from 'vue';// Method to block navigationconst blockNavigation = ref(false);const preventNav = event => {if (!blockNavigation.value) return;event.preventDefault();// Chrome requires returnValue to be setevent.returnValue = "";};// Use `beforeMount` to avoid running during SSRonBeforeMount(() => {// We use the native `beforeunload` eventwindow.addEventListener("beforeunload", preventNav);});// Make sure to always clean up after yourself!onBeforeUnmount(() => {window.removeEventListener("beforeunload", preventNav);});</script>