如何删除 iFrame 添加的 beforeunload 事件监听器?

How to remove beforeunload event listeners added by the iFrame?

如何删除 iFrame 添加的 beforeunload 事件侦听器? 我的情况是我加载的 iframe 将一些 beforeunload 事件添加到 DOM,我想删除它以防会话过期(或针对特定事件说)并且我不想向用户。那么有什么方法可以使用 javascript 从 iframe 中删除事件侦听器吗?任何帮助将不胜感激。

// parent.html

<!DOCTYPE html>
<html>
  <head>
    <title>Parent Frame</title>
    <script>
      window.addEventListener('beforeunload', function(event) {
        console.log('I am the 1st one.');
      });
      window.addEventListener('unload', function(event) {
        console.log('I am the 3rd one.');
      });
    </script>
  </head>
  <body>
    <iframe src="child-frame.html"></iframe>
  </body>
</html>

// child.html

<!DOCTYPE html>
<html>
  <head>
    <title>Child Frame</title>
    <script>
      window.addEventListener('beforeunload', function(event) {
        console.log('I am the 2nd one.');
      });
      window.addEventListener('unload', function(event) {
        console.log('I am the 4th and last one…');
      });
    </script>
  </head>
  <body>
      ☻
  </body>
</html>

单独写添加事件监听函数。以便它可以用于删除侦听器。

function beforeUnload(event) {
   console.log('I am the 2nd one.');
};
// creating event listeners
window.addEventListener('beforeunload', beforeUnload);

// remove when you don't want the listener
window.removeEventListener('beforeunload', beforeUnload);

我只能在 chrome 上重现此行为,FF 似乎不会跨 iframe 触发事件。

我发现的一个解决方法(可能不是最好的)是在离开页面之前删除 iframe:

mainWindow.onbeforeunload = e => { iframe.parentNode.removeChild(iframe) };

这样,事件就不会再冒泡到 iframe 的 window。

// toggle the blocking script
inp.onchange = 
  e => window.onbeforeunload = inp.checked ?
    blockMessage :
    null;

function blockMessage(e){
  iframe.parentNode.removeChild(iframe);
  }
<h3>click "Run code snippet" again</h3>
<label>block iframe's beforeunload<input type="checkbox" id="inp"></label><br>
<iframe id="iframe" src="data:text/html,%3Chtml%3E%3Chead%3E%3Cscript%3Eonbeforeunload%20%3D%20e%20%3D%3E%20%22bye%22%3B%3C%2Fscript%3E%3C%2Fhead%3E%3C%2Fhtml%3E"></iframe>

<!-- Decoded iframe content : 
  <html>
  <head>
  <script>
   onbeforeunload = e => "bye";
  </script>
  </head>
  </html>
-->