0

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?

SteveO
  • 691
  • 2
  • 8
  • 19
  • There is but it's not very customizable, I think all major browsers disabled the ability to give a custom message but they all say something like "Are you sure? You have unsaved changes". What you need is beforeunload, you can run it from within a svelte:window tag as shown in this [answer](https://stackoverflow.com/questions/62567071/bind-sveltewindow-to-onbeforeunload) – JHeth Jul 30 '20 at 01:58
  • 1
    Does this answer your question? [How to Detect Browser Back Button event - Cross Browser](https://stackoverflow.com/questions/25806608/how-to-detect-browser-back-button-event-cross-browser) – johannchopin Jul 30 '20 at 11:25
  • Are you using Sapper? or `svelte-routing`? Which routing library are you using? – Carlos Roso Jul 30 '20 at 22:38

1 Answers1

3

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.

johannchopin
  • 13,720
  • 10
  • 55
  • 101
Carlos Roso
  • 1,435
  • 1
  • 11
  • 14