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

1

5

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?

Arvizu answered 9/2, 2021 at 3:42 Comment(0)
L
8

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}/> 
Lithea answered 9/2, 2021 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.