Inter-Site Communication: Connecting Iframes and Parent Sites Across Domains
Cross-domain communication can present a challenge when working with iframes. If the iframe's domain differs from the parent site, direct access or method calls between them become impossible.
To overcome this hurdle, cross-document messaging provides a solution:
Parent Site to Iframe:
In the parent window, send a message to the iframe's content window:
myIframe.contentWindow.postMessage('hello', '*');
Within the iframe, listen for the message event:
window.onmessage = function(e) { if (e.data == 'hello') { alert('It works!'); } };
Iframe to Parent Site:
In the iframe, send a message to the top-level parent window:
window.top.postMessage('hello', '*')
Within the parent window, listen for the message event:
window.onmessage = function(e) { if (e.data == 'hello') { alert('It works!'); } };
Remember, the '*' in postMessage() allows the message to be broadcast to all listening windows. By employing cross-document messaging, you can establish communication between an iframe and its parent site, even across different domains.
The above is the detailed content of How Can I Enable Cross-Domain Communication Between an Iframe and its Parent Site?. For more information, please follow other related articles on the PHP Chinese website!