如何从另一个iFrame中清除iFrame的内容

How to clear the contents of an iFrame from another iFrame

本文关键字:iFrame 清除 另一个      更新时间:2023-09-26

我有一个带有<iframe class="header"<iframe class="pageBody"wrapperPage.html。在header中有一个链接<a class="clearLink",单击该链接应清除pageBody的内容。

到目前为止,上述想法的以下实现不起作用。请帮我解决这个问题。

请注意headerpageBody分别从不同的包含文件加载。

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>

尝试使用通道消息

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>

您可以从iFrame中获得主窗口的引用,如下所示:窗口.父引用

然后,您可以在主窗口(或仅在其他iFrame中)中分配一个事件来捕获触发器或函数以进行管理。

例如:

  • 在pageBody.html中编写一个与自定义事件关联的函数
  • header.html iFrame中的单击功能获取窗口引用
  • 搜索已分配自定义事件的目标元素
  • 启动活动

我希望它能帮助你。