【问题标题】:Bind <svelte:window> to `onbeforeunload`将 <svelte:window> 绑定到 `onbeforeunload`
【发布时间】:2020-10-15 10:07:50
【问题描述】:

我希望绑定到&lt;svelte:window&gt;,但没有运气。

<!-- 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.onbeforeunloadnull

我最终选择了window.onbeforeunload = () =&gt; true,但想知道为什么对元素的设置不起作用。

【问题讨论】:

    标签: svelte svelte-3


    【解决方案1】:

    使用svelte:window时需要设置事件returnValue

    <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}/>
    

    之所以这样,是因为在svelte中写on:event={handler},就相当于写node.addEventListener(event, handler, options)

    原来,当使用addEventListener附加beforeunload,然后you need to set the event returnValue and/or return a value

    但请注意,并非所有浏览器都支持此方法,有些浏览器 而是要求事件处理程序实现两个遗留的之一 方法:

    • 将字符串分配给事件的 returnValue 属性
    • 从事件处理程序返回一个字符串。

    使用window.onbeforeunload注册事件只需要返回值

    【讨论】:

      猜你喜欢
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 2011-11-01
      • 1970-01-01
      • 2011-06-04
      • 2019-01-22
      相关资源
      最近更新 更多