绑定 <svelte:window>到`onbeforeunload` [英] Bind <svelte:window> to `onbeforeunload`
问题描述
我希望绑定到
但没有成功.
<!-- 不起作用 --><svelte:window on:beforeunload={() =>真}/><!-- 不起作用--><svelte:window on:onbeforeunload={() =>真}/><!-- 不起作用--><svelte:window on:beforeUnload={() =>真}/>
在所有情况下,window.onbeforeunload
都是 null
我最后只用了 window.onbeforeunload = () =>对
但想知道为什么在元素上设置不起作用.
使用svelte:window
returnValue
<svelte:window on:beforeunload={beforeUnload}/>
这样做的原因是在svelte中写on:event={handler}
,等价于写node.addEventListener(event, handler, options)
>
事实证明,当使用 addEventListener
附加 beforeunload
时,然后 你需要设置事件returnValue
和/或返回一个值
但是请注意,并非所有浏览器都支持此方法,有些浏览器而是要求事件处理程序实现两个遗留问题之一方法:
- 为事件的 returnValue 属性分配一个字符串
- 从事件处理程序返回一个字符串.
使用window.onbeforeunload
注册事件只需要返回值
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.
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
这篇关于绑定 <svelte:window>到`onbeforeunload`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!