Reputation: 963
I have a component that allows a user to edit their state. This triggers a notSaved
variable. I have a beforeunload
event handler to handle reload and exiting the page to remind the user to save their state, but using SvelteKit, using the back button in the browser doesn't seem to trigger the beforeunload
event. I also have a popstate
event handler, because that is triggered when the back button is clicked, but I can't figure out how to prevent the window.history
from changing if the notSaved
variable is true.
Is there a way in SvelteKit to trigger a Changes you made may not be saved.
popup similar to the one that is triggered on a beforeunload
event when the back or forward button is pressed?
Upvotes: 3
Views: 1442
Reputation: 5942
You can use the beforeNavigate
function to be notified of a navigation intent in order to potentially block it, for example:
<script>
import { beforeNavigate } from '$app/navigation';
let unsavedWork = false;
let value = 0;
beforeNavigate(({ from, to, cancel }) => {
if (unsaved) {
cancel();
showUnsavedWorkPopup();
}
});
function onChange() {
...
unsavedWork = true;
}
async function save() {
await ...
unsavedWork = false;
}
</script>
<input type="number" bind:value on:change={onChange}>
Upvotes: 4