Vritti Gautam
Vritti Gautam

Reputation: 61

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

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?

Upvotes: 6

Views: 1867

Answers (1)

Jérémie B
Jérémie B

Reputation: 11032

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}/> 

Upvotes: 9

Related Questions