How to remove beforeunload event listeners added by the iFrame?

Viewed 3696

How can I remove beforeunload event listeners added by the iFrame? My case is the iframe I load add some beforeunload events to the DOM, which I want to remove in case the session expires(or say for a particular event) and I don't want to show the confirmation message to the user. So is there any way I can remove event listeners from the iframe using javascript? Any help will be appreciated.

// 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 Answers
Related