Reputation: 751
I would like to fully control navigation in my Svelte SPA App.
Is there a way to trap the back, forward, and refresh buttons so that I can give a warning about loosing the page?
Upvotes: 0
Views: 3886
Reputation: 1495
Assuming you're not using Sapper or a third-party Svelte routing library, you can achieve that using beforeunload
as proposed in the comments. Here's a snippet with TypeScript.
<script lang="ts">
export let name: string;
function beforeunload(event: BeforeUnloadEvent) {
event.preventDefault();
return event.returnValue = '';
}
</script>
<p>{name}</p>
<svelte:window on:beforeunload={beforeunload}/>
on:beforeunload
might throw a type error but it should work fine.
Upvotes: 3