preventChange()

Sometimes you need to prevent the user from leaving the current route; for instance, a form might has been changed and needs to be saved before the user forgets about it. The preventChange() method allows implementing that.

preventUnload()

Also, there are situations where you want to prevent the current window from being closed - for instance, also when a form has changed. The preventUnload() action is very handy for that.

Demo

So here is an example of how to use both: If you change the input below, Elegua will not allow you to navigate to any other links until you either save the form. Try changing the value and navigating to any links, and you'll see you can't. Also, since preventUnload() is used, if you try to close the window (e.g. Ctrl-W), the browser will ask for confirmation.

Thsee are the handlers used on this very page:

  <script lang="ts">
  onMount(() => {
    preventChange(() = > {
      if (isDirty_) {
        alert('Please save or cancel changes before navigating away');
        return true;
      }
    });
  });

  onDestroy(() => {
    // reset handler
    preventChange();
  });
</script>
<svelte:window use:preventUnload={() => isDirty_} /=>

You can also use the checkbox below for locking yourself into the current page (can't navigate away, nor close the window):

Lock into this form

See this page's source code for more details.