我希望绑定到<svelte:window>
但没有运气。
<!-- doesn't work -->
<svelte:window on:beforeunload={() => true} />
<!-- doesn't work -->
<svelte:window on:onbeforeunload={() => true} />
<!-- doesn't work -->
<svelte:window on:beforeUnload={() => true} />
在所有情况下,window.onbeforeunload
is null
我最终只是去了window.onbeforeunload = () => true
但想知道为什么元素上的设置不起作用。
您需要设置事件returnValue
使用时svelte:window https://svelte.dev/docs#template-syntax-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}/>
这样做的原因是,写作on:event={handler}
in svelte,相当于写作node.addEventListener(event, handler, options)
事实证明,在附加时beforeunload
using addEventListener
, then 你需要设置事件returnValue和/或返回一个值 https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
但请注意,并非所有浏览器都支持此方法,有些浏览器
相反,要求事件处理程序实现两个旧版本之一
方法:
- 将字符串分配给事件的 returnValue 属性
- 从事件处理程序返回一个字符串。
使用注册事件window.onbeforeunload
只需要一个返回值
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)