繁体   English   中英

如何使用Javascript PostMessage使用不同协议将iframe外部的元素定位

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

我在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的原点

otherWindow的文件的方案,主机名或端口不匹配所提供targetOrigin

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

如果您不在乎允许读取哪个来源,请使用"*"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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