Trigger an event to warn the customer to save his changes in svelte

1.5k views Asked by At

I would like to warn a user to save his changes (form changes)before leaving the page. I want to trigger this alert if he clicks anywhere on the window. It could be the back button or reload or any navigation links that are available on the page.Can somebody pls help?

1

There are 1 answers

0
Jérémie B On

You should use the 'beforeunload' event on window, see here

In svelte, you subscribe to an event on window with the <svelte:window/> special element:

<script>

  let dirty = true; // document has changes to save

  function beforeUnload() {
    if (dirty) {
        event.preventDefault();
        event.returnValue = '';
        return '';
    }
  }

</script>

<svelte:window on:beforeunload={beforeUnload}/>