Home > Article > Web Front-end > How Can Iframes on Different Domains Communicate Using PostMessage?
Cross-Domain Communication between Iframe and Parent Site
When an iframe resides on a different domain than its parent site, direct communication through methods or content document access is not feasible. In such cases, the solution lies in cross-document messaging.
Parent to Iframe Communication
In the parent window:
myIframe.contentWindow.postMessage('hello', '*');
In the iframe:
window.onmessage = function(e) { if (e.data == 'hello') { alert('It works!'); } };
Iframe to Parent Communication
In the parent window:
window.onmessage = function(e) { if (e.data == 'hello') { alert('It works!'); } };
In the iframe:
window.top.postMessage('hello', '*')
Remember, the asterisk (*) in the postMessage() function represents wildcard, allowing the message to be received by any origin.
The above is the detailed content of How Can Iframes on Different Domains Communicate Using PostMessage?. For more information, please follow other related articles on the PHP Chinese website!