How to clear the contents of an iFrame from another iFrame

Try using Channel messaging

wrapperPage.html

<body>
<div class=non-floater>
    <iframe class="header" src="https://stackoverflow.com/questions/33645685/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>

Leave a Comment