Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

javascript - How do I postMessage to a sibling iFrame

I'm looking for a way to postMessage to a sibling iFrame without any javascript in the parent page. The difficulty I'm having is trying to get the window object for the other iFrame from the first iFrame

The page would be laid out something like this:

html body (http://host.com/)
  iFrame#a (http://me.com/a)
  iFrame#b (http://me.com/b)

From iFrame#a I'm trying to do:

(iFrame#b window).postMessage(...)

The problem is I don't know how to get the window object for iFrame#b from within iFrame#a. parent.getElementById() and other functions are subject to XSS restrictions. I just want to emit a postMessage to all other iFrames on the parent page that are from my domain http://me.com/ in the example above.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While it is true that it is not possible to interact with another window/iframe that is on another domain, it is possible to get references to such a window/iframe and all the child iframes embedded into that window/iframe. The way to do it is to use window.top.frames (to access the top window object) or window.parent.frames (to access the direct parent window object, while there may be other higher-level ancestors). No need to use getElementById or other DOM-related function. See this for more info: https://developer.mozilla.org/en-US/docs/DOM/window.frames

The window.frames property returns an array-like object which you can then iterate over and do a postMessage on each iframe. This will not trigger the same-origin restrictions since you are not interacting with any window in any way except than using postMessage on them. Since you want to do a postMessage on every iframe from a specific domain, you can just do:

var frames = window.parent.frames;
for (var i = 0; i < frames.length; i++) { 
  frames[i].postMessage("hello", targetDomain);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...