How to clear the contents of an iFrame from another iFrame
I have a wrapperPage.html
with an <iframe class="header"
and <iframe class="pageBody"
. In header
there is a link, <a class="clearLink"
, which when clicked should clear the contents of pageBody
.
So far the following implementation of the above idea doesn't work. Please help me resolve this.
Please NOTE that, header
and pageBody
are each loaded from different included files.
wrapperPage.html
<div class=non-floater>
<iframe class="header" src="header.html"></iframe>
<iframe class="pageBody" src="pageBody.html" />
</div>
header.html :
<script type="text/javascript">
$(document).ready(function() {
$(".clearLink").on("click", function() {
$('.pageBody').contents().find("body").html('');
});
});
</script>
<a class="clearLink" href="#">Navigation Button</a>
pageBody.html :
<div class="panel-body">This is the body</div>
Solution 1:
Try using Channel messaging
wrapperPage.html
<body>
<div class=non-floater>
<iframe class="header" src="header.html"></iframe>
<iframe class="pageBody" src="pageBody.html" />
</div>
<script>
var channel = new MessageChannel();
var header = $(".header")[0].contentWindow;
var pageBody = $(".pageBody")[0].contentWindow;
header.onload = function() {
this.postMessage("","*", [channel.port2])
};
channel.port1.onmessage = function(e) {
if (e.data === "clicked") {
$(pageBody.document.body).html("")
}
}
</script>
</body>
header.html
<body>
<a class="clearLink" href="#">Navigation Button</a>
<script>
var port;
onmessage = function(e) {
port = e.ports[0];
}
$(".clearLink").on("click", function(e) {
port.postMessage("clicked");
});
</script>
</body>