多个OnBeforeUnload

Jay*_*esh 7 javascript jquery

我正在编写一个用作插件的JS.JS有一个onbeforeunload事件.

我想要建议,以便我的onbeforeunload事件不会覆盖现有的onbeforeunload事件(如果有的话).我可以将我的onbeforeunload附加到现有的吗?

谢谢.

Jul*_* D. 11

如果您不使用事件观察但onbeforeunload直接附加处理程序(您不应该这样做),则只需要处理此问题.如果是这样,请使用类似的东西来避免覆盖现有的处理程序.

(function() {
    var existingHandler = window.onbeforeunload;
    window.onbeforeunload = function(event) {
        if (existingHandler) existingHandler(event);

        // your own handler code here
    }
})();
Run Code Online (Sandbox Code Playgroud)

不幸的是,您无法阻止其他(稍后)脚本覆盖您的处理程序.但同样,这可以通过添加事件侦听器来解决:

$(window).unload(function(event) {
    // your handler code here
});
Run Code Online (Sandbox Code Playgroud)

  • 最好放弃第一个解决方案,只需使用 window.addEventListener('beforeunload', () => {/*事件处理*/}); 想要多少次都可以 (2认同)

Lun*_*fel 8

我觉得这还没有得到完全回答,因为没有显示使用示例addEventListener(但 MAZZTer 指出了addEventListener解决方案)。我的解决方案与 Julian D. 相同,但不使用 jQuery,只使用原生 javascript。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Before Unload</title>
</head>
<body>
    <p>Test</p>

    <script>
      window.addEventListener('beforeunload', function (event) {
        console.log('handler 1')
        event.preventDefault()
        event.returnValue = ''
      });

      window.addEventListener('beforeunload', function (event) {
        console.log('handler 2')
      });
    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在此示例中,将执行两个侦听器。如果beforeunload设置了任何其他侦听器,则不会覆盖它们。我们将得到以下输出(不保证顺序):

handler 1
handler 2
Run Code Online (Sandbox Code Playgroud)

而且,重要的是,如果一个或多个事件侦听器执行了event.preventDefault(); event.returnValue = '',则会出现询问用户是否真的要重新加载的提示。

如果您正在编辑表单并同时通过 ajax 下载文件并且不希望丢失任何这些操作的数据,这将非常有用。每一个都可以有一个监听器来防止页面重新加载。

const editingForm = function (event) {
  console.log('I am preventing losing form data')
  event.preventDefault()
  event.returnValue = ''
}

const preventDownload = function (event) {
  console.log('I am preventing a download')
  event.preventDefault()
  event.returnValue = ''
}

// Add listener when the download starts
window.addEventListener('beforeunload', preventDownload);
// Add listener when the form is being edited
window.addEventListener('beforeunload', editingForm);

// Remove listener when the download ends
window.removeEventListener('beforeunload', preventDownload);
// Remove listener when the form editing ends
window.removeEventListener('beforeunload', editingForm);
Run Code Online (Sandbox Code Playgroud)

  • 这必须标记为答案,因为它不受外部库和全局挂钩的影响 (2认同)