[英]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.