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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With