[英]How to target an element outside an iframe with different protocol using Javascript postMessage
I have a button in an iframe and I wish that, it triggers another button, which is found outside the iframe, when clicked. 我在iframe中有一个按钮,但我希望它触发单击后在iframe外部找到的另一个按钮。
Here is a piece of code that I have been trying to work out. 这是我一直在尝试的一段代码。
The HTML 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>
in Parent html 在父html中
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if(event.data == "click!") {
$('a.close').trigger('click');
}
}
in iframe 在iframe中
var targetOrigin = window.location.host;
top.window.postMessage("click!", targetOrigin);
targetOrigin = window.location.host
is going to give you the hostname of the page you are posting from but: targetOrigin = window.location.host
将为您提供从中发布页面的主机名,但:
targetOrigin
Specifies what the origin ofotherWindow
must be for the event to be dispatched指定要分派事件的
otherWindow
的原点
and 和
the scheme, hostname, or port of otherWindow's document does not match that provided in
targetOrigin
otherWindow的文件的方案,主机名或端口不匹配所提供
targetOrigin
so you need to provide a complete origin (such as http://example.com:234
), not just the hostname. 因此您需要提供一个完整的来源(例如
http://example.com:234
),而不仅仅是主机名。
If you don't care which origin is allowed to read the message, use "*"
. 如果您不在乎允许读取哪个来源,请使用
"*"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.