跨域postMessage,识别iFrame [英] Cross domain postMessage, identify iFrame
问题描述
我使用 postMessage
将事件从iframe发送到其父文档。我可以控制双方,但内容来自两个不同的域。
I use postMessage
to send events from an iframe to it's parent document. I have control over both sides but the content comes from two different domains.
我的简单问题是,我无法识别iFrame里面的父回调方法。实施方式如下:
My simple problem is, that i can not identify the iFrame inside of it's parent callback method. The implementation looks like this:
在iFrame中:
parent.postMessage(JSON.stringify({action: "closeView" }),'*');
在父窗口中:
window.addEventListener('message',function(event) {
if(event.origin !== 'https://example.com')
return;
// Parse message back to json
var messageObject = JSON.parse(event.data);
var source = event.source;
/* this is returning: Window -URL- */
console.log( source );
/* This will throw Permission denied, although this code is inside of "parent" */
console.log(source.parentNode);
},false);
我想要识别iframe的某个父元素,它是(逻辑上)父文档。
I want to identify a certain parent element of the iframe, which is (logically) inside of the parent document.
当我尝试使用 event.source.parentNode
或一些jQuery对象时,Firefox说,我不能这样做以防止XSS,错误:错误:权限被拒绝访问属性parentNode
When i try to use event.source.parentNode
or some jQuery on said object, Firefox says, i can not do this to prevent XSS, error: Error: Permission denied to access property 'parentNode'
我可以得到iFrame的父元素,触发 postMessage
事件侦听器?
How can i get the parent element of the iFrame, that triggered the postMessage
event listener?
推荐答案
可以使用窗口名称,因为它们从iframe标记传递到iframe上下文。
you can use window names for this, as they pass from iframe tag to iframe context.
父文档:
<iframe name=fr2 src="data:text/html,%3Chtml%3E%0A%20%3Cscript%3E%20parent.postMessage%28%7Bname%3A%20window.name%7D%2C%20%22*%22%29%3B%3C/script%3E%0A%3C/html%3E"></iframe>
<iframe name=fr3 src="data:text/html,%3Chtml%3E%0A%20%3Cscript%3E%20parent.postMessage%28%7Bname%3A%20name%7D%2C%20%22*%22%29%3B%3C/script%3E%0A%3C/html%3E"></iframe>
<script>onmessage = function(e){ // use real event handlers in production
alert("from frame: " + e.data.name);
};</script>
iframe doc:
iframe doc:
<html>
<script> parent.postMessage({name: name}, "*");</script>
</html>
会提示fr2,然后是fr3。
,您就可以使用attrib CSS选择器轻松使用 name attrib在父DOM中查找iframe。
which alerts "fr2", then "fr3". you can then easily use the name attrib to find the iframe in the parent DOM using attrib CSS selectors.
演示window.name + iframe概念: http://pagedemos.com/namingframes/
illustrative demo of window.name+iframe concept: http://pagedemos.com/namingframes/
这种痛苦的简单方法也免疫于同一网址iframe产生的问题。
this painfully simple approach is also immune to issues arising from same-url iframes.
这篇关于跨域postMessage,识别iFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!