简体   繁体   中英

Alert user before leaving web page with unsaved changes on form

I have forms in my application, all in one page, and I change them on button click without refreshing page.

How can I secure the form in such a way that if someone navigates away, change form or closes the browser tab, they should be prompted to to confirm they really want to leave the form with unsaved data?

Yes I know about onbeforeunload event, but it wouldn't work if I change form without refreshing page

Hope someone understand me, and can help with an advice

PS I work with svelte

Whether there was a navigation or not is irrelevant, you just have to react to changes, eg you can handle a change event on the form -level to add the beforeunload handler which adds the confirmation question.

Something like:

<script>
  function onChange() {
    window.addEventListener('beforeunload', e => {
      e.preventDefault()
      return e.returnValue = "Are you sure you want to exit?";
    });
  }
</script>

<form on:change={onChange}>
  ...
</form>

(Maybe add a flag & if to prevent adding duplicate listeners.)

The change event only captures common interactions with native input elements. If the event is stopped from reaching the form (or whatever container you add the listener on) this will not work. It will also not capture more complex logic, like adding an item to some list.

Depending on your concrete code, you may need to handle additional/different events or changes.

If you use a client-side router of some kind you also have to signal to it, that it should not navigate away because beforeunload will not be triggered. How this is done depends entirely on the router being used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM