简体   繁体   English

从跨网域的iframe与窗口进行通信

[英]Communicate to window from iframe on cross-domain

Let's say I have have a webpage with domain name a.example.com which has an iframe with domain b.example.com (Not satisfying same origin policy). 假设我有一个域名为a.example.com的网页,而该iframe的域名为b.example.com (不满足相同的原始政策)。

Now I open a new window using window.open from the iframe with the same domain, that is b.example.com . 现在,我从具有相同域(即b.example.com)的iframe中使用window.open打开一个新窗口。

My task is to send message back to the iframe. 我的任务是将邮件发送回iframe。

window.opener is empty for the opened window. window.opener对于打开的窗口是空的。

I read that I can communicate using postMessage, but to what element I should post the data to. 我读到可以使用postMessage进行通信,但是应该将数据发布到哪个元素。 How to get the reference of parent window (ie the iframe). 如何获取父窗口(即iframe)的引用。

Who says the iframe is yours? 谁说iframe是您的? The browser can't trust you in this respect because someone could be messing with your page and load something else instead, so modern browsers lock iframe communication down completely. 在这方面,浏览器无法信任您,因为有人可能会弄乱您的页面并加载其他内容,因此现代浏览器将iframe通讯完全锁定。 Even with access control, you won't get two way communication going. 即使使用访问控制,也不会实现双向通信。

However, if you can make the iframe and the owning document "speak the same language", then you can use postMessage communication: postMessage basically posts strings (and only strings, so any JS objects need to be JSON.stringified) into a "visible to everyone" bucket of strings. 但是,如果可以使iframe和所属文档“说相同的语言”,则可以使用postMessage通信:postMessage基本上将字符串(并且字符串,因此所有JS对象都需要JSON.stringified)发布为“可见”给所有人”一堆字符串。 Any document context can post messages, and every context can decide to listen to whether new messages are posted. 任何文档上下文都可以发布消息,并且每个上下文都可以决定侦听是否发布了新消息。 If they are, then you can make the iframe send messages that the owning window can parse, and vice versa. 如果是这样,则可以使iframe发送拥有窗口可以解析的消息,反之亦然。

In order to for their site, which holds the iframe that you control the contents of, to get information back from a window that is opened by clicking something within your contents, they have to allow access to your site on theirs. 为了使他们的网站(其中包含您控制内容的iframe能够从通过单击内容中打开的窗口打开的窗口中获取信息,他们必须允许访问自己网站上的内容。 If you just want data from a window that is opened by clicking something on the page that you control it's like: 如果您只想从通过单击您控制的页面上的某个东西打开的窗口中获取数据,例如:

var newWindow = open('yourURL.php');
var someElement = newWindow.document.getElementById('someId');
console.log(someElement.value); // assuming it's an input

If you want information from the page that opened your other page from withing the newly opened window it's like: 如果您希望从打开新页面的页面获取信息而不是新打开的窗口,则如下所示:

var openerElement = opener.document.getElementById('openerWindowId');
console.log(openerElement.innerHTML); // assuming it's not an input

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

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