How to clear the contents of an iFrame from anothe

2019-01-01 16:38发布

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>

2条回答
听够珍惜
2楼-- · 2019-01-01 16:47

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>
查看更多
余生请多指教
3楼-- · 2019-01-01 17:00

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.

查看更多
登录 后发表回答