Communication between iFrames? [duplicate]

2019-01-11 19:19发布

This question already has an answer here:

How can you make two iFrames talk to each other? For example I was a element value off the 2nd iframe and the 1st iframe has the display element on it. I need to get the value off the 2nd frame to the 1st. How would I do this? Don't say use cookies, cause that will hurt with massive sum of data.

3条回答
女痞
2楼-- · 2019-01-11 19:55

First things first, the only way a frame can interact outside of it's self is if the content loaded in both places is from the same domain otherwise you're going to get a CORS error.

Assuming that's all gravy, I'd create an manager object on the window object of the parent frame.

window.Mgmt = {
    frame1: $('iframe#frame1'),
    frame2: $('iframe#frame2')
}

then in either of the iframes you should be able to access that object using window.parent.Mgmt.frame1, etc

查看更多
The star\"
3楼-- · 2019-01-11 20:07

If the <iframe> elements are served from the same domain, then they can access each other directly. For example, in iframe1 you could do:

document.getElementById('someDiv').innerHTML = 
    top.document.getElementById('otherIframe').contentWindow.
    document.getElementById('someOtherDiv').innerHTML;
查看更多
做个烂人
4楼-- · 2019-01-11 20:07

I'll warn you first off that you will need full code-modification abilities for both iframes. Iframes are treated with strict security; otherwise, I could make a domain "bunkofamerica.com", put "bankofamerica.com" in an iframe, and then analyze the user's password as they type it. (Banks tend to have iframe-busting code anyway, but still...)

You're looking for this native function: https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage

And here's a github library my company uses to make this more cross-browser compatible: https://github.com/daepark/postmessage

jbabey is correct, if iframes are in the same domain and protocol, then it's easier.

Opera Docs explained this with best relevant examples https://dev.opera.com/articles/window-postmessage-messagechannel/#channel

查看更多
登录 后发表回答