如何在 angular 中在 I-Frame 和父窗口之间进行通信

How to do communication between I-Frame and parent window in angular

提问人:codegeek 提问时间:9/21/2021 最后编辑:codegeek 更新时间:9/21/2021 访问量:4361

问:

任何建议如何使 Iframe 与父窗口通信。 场景:

在 Iframe 内部,同一域中有一个单独的网站,具有多个链接。 当用户在 iframe 中单击“链接”时,该值应传播到父窗口。

我尝试跟踪 iframe 中的点击事件并获取 iFrame.src,但没有 工作。

HTML格式 :

 <iframe #Iframe class="iframek" (click)="onChange(kIframe)" sandbox="allow-same-origin allow-scripts allow-top-navigation" id="iframe_k"   [src]='safeUrl' scrolling="auto" frameborder="0" allowfullscreen=true wmode="transparent" name="kiframe"></iframe>

onChange(iframe) {
  console.log("onchange");
  if(iframe.contentWindow)
  {
    console.log(iframe.contentWindow.document);
  }
  else{
    console.log(iframe.contentWindow);
  }
  
  console.log(iframe.getAttribute('src'));
  
}
JavaScript iframe angular10

评论

0赞 alchemist95 9/28/2021
看看这个答案: stackoverflow.com/a/16657480/4633925 对于相同的域 iframe,您不需要发布消息。您可以访问 iframe,反之亦然。

答:

1赞 pawel2101 9/21/2021 #1

您应该在 Window 对象之间使用跨域通信

有关详细信息,请参阅此答案:如何在 iframe 和父站点之间进行通信?

若要实现方案,请执行以下操作:

  1. 跟踪 iframe 中锚点上的所有点击事件
  2. 单击后,读取单击的锚点的 href 属性,并使用 window.postMessage() 将其发送到父窗口(请记住在单击事件上调用 preventDefault() 以防止在 iframe 内导航)
  3. 在父窗口中接收事件并导航