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

标签 javascript iframe browser addeventlistener onbeforeunload

如何删除 iFrame 添加的 beforeunload 事件监听器? 我的情况是我加载的 iframe 添加了一些 beforeunload 事件到 DOM,我想删除这些事件,以防 session 过期(或者说对于特定事件)并且我不想向用户显示确认消息。那么有什么方法可以使用 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);

关于javascript - 如何删除 iFrame 添加的 beforeunload 事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45272776/

相关文章:

javascript - React Mobile 打开时带有按钮,但不是可点击的组件

javascript - 如何让音乐播放器在网站上连续播放

forms - Chrome : Fill out same form many times for testing

gwt - 停止 GWT 应用程序中的浏览器脚本缓存

javascript - 避免循环访问由 mongodb 和 express 生成的 URL

javascript - 看不懂这个运行时对照表的意思

javascript - 使用 Javascript 将文本字段添加到 HTML 表单时出错

javascript - 如何获取嵌入的 YouTube 视频以自动播放建议的视频?

javascript - 如何获取iframe内内容的滚动位置

javascript - SCRAM 客户端 Javascript 实现/示例/库?