来自同一域的两个 iframe 之间使用 postMessage 进行通信

Asu*_*sur 4 html iframe postmessage same-origin-policy

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]
Run Code Online (Sandbox Code Playgroud)

I tried following lines to access DOM of iframes

parent.frame[x].contentWindow returns null,

parent.frame[x].document.getElementsByTagName("body") returns null
Run Code Online (Sandbox Code Playgroud)

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 document

mea*_*dre 5

如果需要跨窗口同域通信,可以通过 进行设置localStorage。当您将项目添加到 时localStorage,您会"storage"在同一域的所有其他窗口/iframe/选项卡中获取窗口事件。

因此,您基本上localStorage.setItem('name', 'value')在一个 iframe 中收听window.addEventListener('storage', (event) => {/* handle message */})并收到消息。