如何使用Javascript postMessage将不同协议的iframe外部的元素作为目标

How to target an element outside an iframe with different protocol using Javascript postMessage

本文关键字:外部 iframe 元素 目标 协议 Javascript 何使用 postMessage      更新时间:2023-09-26

我在iframe中有一个按钮,我希望它在单击时会触发另一个位于iframe外部的按钮。

这是我一直在努力解决的一段代码。

HTML

<body>
 <iframe id="layer-frame" src="https://somepage.com">
  <a href="https://page2.com" target="_blank" id="js-gopage2" class="js-iframepostmsg" alt="CLICK HERE TO Edit your profile">Edit your profile</a>
 </iframe>
 <div>
  <a class="close" href="#">Close<span></span></a>
 </div>
</body>

在父html 中

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
 if(event.data == "click!") {
  $('a.close').trigger('click');
 }
}

在iframe 中

var targetOrigin = window.location.host;
top.window.postMessage("click!", targetOrigin);

targetOrigin = window.location.host将为您提供您从发布的页面的主机名,但是:

targetOrigin
指定要调度的事件的otherWindow的来源

其他Window文档的方案、主机名或端口与targetOrigin 中提供的不匹配

因此,您需要提供一个完整的原点(如http://example.com:234),而不仅仅是主机名。

如果您不关心允许哪个来源读取消息,请使用"*"