简体   繁体   中英

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>

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>

You can get the reference of the main window from an iFrame as follow: Window.Parent reference

Then, you can assign an event to catch a trigger or a function in the main window (or only in the other iFrame) to manage it.

For example :

  • Write a function in pageBody.html associated to a custom event.
  • Get window reference from your click function in your header.html iFrame.
  • Search target element which has your custom event assigned.
  • Fire the event

I would hope it help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM