简体   繁体   English

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

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

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