How to trigger onunload event when removing iframe ?
Asked Answered
U

1

5

How can the iframe's unload event be triggered when removing it?

Using the code below, when removeChild(iframe) is called, the onunload event is not triggered.

<!-- parent.html -->
<html>
  <head>
    <title>remove iframe</title>
    <script type="text/javascript">
      window.onload = function() {
        var button = document.getElementsByTagName("BUTTON")[0];
        button.onclick = function() {
          document.body.removeChild(document.getElementsByTagName("IFRAME")[0]);
        };
      };
    </script>
  </head>
  <body>
    <iframe src="./son.html" />
    <button>Remove iframe</botton>
  </body>
</html>
<!-- son.html -->
<html>
  <head>
    <title>son html</title>
    <script type="text/javascript">
      window.onload = function() { alert("hello"); };
      window.onunload = function() { alert("world!"); };
    </script>
  </head>
  <body style="background-color:#aaccee;">
  </body>
</html>

How can I trigger it?

Urbanism answered 30/12, 2011 at 7:13 Comment(0)
K
11

Before remove the frame, you can set the src attribute of the iframe element to "about:blank", check if this make the iframe trigger onunload event.

EG:

var iframe = document.getElementsByTagName("IFRAME")[0];
iframe.src = "about:blank";
document.body.removeChild(iframe);
Knife answered 30/12, 2011 at 7:23 Comment(1)
it works great in firefox, but not in Chrome. Any ideas?Unutterable

© 2022 - 2024 — McMap. All rights reserved.