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

时间:2017-07-24 04:44:22

标签: javascript iframe browser addeventlistener onbeforeunload

如何删除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>

2 个答案:

答案 0 :(得分:1)

我只能在chrome上重现此行为,FF似乎无法在iframe中触发事件。

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

child.getRef().child("status").setValue("accepted");

这样,该事件不再会出现在iframe的窗口中。

&#13;
&#13;
Query query = db.orderByChild("r_id").equalTo(f_id);
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot child : dataSnapshot.getChildren()) {
            String child_s_id = (String) child.child("s_id").getValue();
            String child_status = (String) child.child("status").getValue();

            if (child_s_id.equals(id))
                child.getRef().child("status").setValue("accepted");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

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

答案 1 :(得分:0)

分别编写添加事件监听器功能。这样它就可以用来删除监听器。

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);