Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger onunload event when removing iframe ?

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?

like image 752
consatan Avatar asked Dec 30 '11 07:12

consatan


People also ask

What triggers beforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

What is onbeforeunload event?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

What is onload and Onunload?

The onunload utility, which unloads data from a database, writes a database or table into a file on tape or disk. The onload utility loads data that was created with the onunload command into the database server.


1 Answers

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);
like image 166
TimonWang Avatar answered Sep 19 '22 23:09

TimonWang