Communication between two iframes from the same domain with postMessage
I have two iframes from the same domain, which are hosted in document from another domain. The problem is these iframes cannot communicate with each other through postMessage. I cant even access the DOM of iframe1 from iframe2 even though they belong to same domain. Is there any solution ????
I used following options to refer the required iframe.
parent.frame[x]
I tried following lines to access DOM of iframes
parent.frame[x].contentWindow returns null,
parent.frame[x].document.getElementsByTagName("body") returns null
Update:
I guess my question is not clear enough. There is no problem with postMessage api, the actual problem is browser creates a custom frameset around the iframe document, in my case!
So parent.frame[x]
won't point to the iframe window, instead it points to the custom frameset inside the iframe window.
Following question explains the problem well.
Prevent browser from loading a custom frameset in an iframe's docume开发者_StackOverflow中文版nt
If you want cross-window same-domain communication, you can set it up via localStorage
. When you add an item to localStorage
, you get window "storage"
event in all other windows / iframes / tabs of the same domain.
So, you basically localStorage.setItem('name', 'value')
in one iframe while you listen to window.addEventListener('storage', (event) => {/* handle message */})
and you get the message.
Take a look at the following description of the postMessage function and how it could be used. So in frame1 you call the postMessage
method and in frame2 you subscribe for notifications. Obviously the browser you are using must support this API.
There's also a very nice jQuery plugin which wraps this API and simplifies its usage. It also works in browsers that do not support the postMessage
method by using the hash portion of the url.
精彩评论