Bind <svelte:window> to `onbeforeunload`

别来无恙 提交于 2021-02-07 10:21:08

问题


I was hoping to bind to <svelte:window> but have no luck.

<!-- doesn't work -->
<svelte:window on:beforeunload={() => true} />

<!-- doesn't work -->
<svelte:window on:onbeforeunload={() => true} />

<!-- doesn't work -->
<svelte:window on:beforeUnload={() => true} />

in all instances, window.onbeforeunload is null

I ended up just going with window.onbeforeunload = () => true but was wondering why setting on the element didn't work.


回答1:


You need to set the event returnValue when using svelte:window

<script>

  function beforeUnload() {
    // Cancel the event as stated by the standard.
    event.preventDefault();
    // Chrome requires returnValue to be set.
    event.returnValue = '';
    // more compatibility
    return '...';
  }

</script>

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

The reason for this is that writing on:event={handler} in svelte, is equivalent to writing node.addEventListener(event, handler, options)

It turns out that when attaching beforeunload using addEventListener, then you need to set the event returnValue and/or return a value

However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods:

  • assigning a string to the event's returnValue property
  • returning a string from the event handler.

Registering the event using window.onbeforeunload only requires a return value



来源:https://stackoverflow.com/questions/62567071/bind-sveltewindow-to-onbeforeunload

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!