开发者

Communication between two iframes from the same domain with postMessage

开发者 https://www.devze.com 2023-03-19 05:28 出处:网络
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 D

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号