Cross-Domain Communication between iFrames and Parent Site
When an iframe's website resides on a different domain, direct communication between the iframe and the parent site becomes a challenge. However, cross-document messaging can bridge this gap.
Parent-to-Iframe Communication
In the parent window, you can use postMessage() to send messages to the iframe's contentWindow:
myIframe.contentWindow.postMessage('hello', '*');
On the iframe side, an onmessage event can capture and process the message:
window.onmessage = function(e) { if (e.data == 'hello') { alert('It works!'); } };
Iframe-to-Parent Communication
To send messages from the iframe to the parent window, you can use postMessage() with window.top as the target:
window.top.postMessage('hello', '*')
In the parent window, the onmessage event will receive and process the iframe's message:
window.onmessage = function(e) { if (e.data == 'hello') { alert('It works!'); } };
By utilizing cross-document messaging, you can establish bidirectional communication between an iframe from a different domain and its parent site.
The above is the detailed content of How Can I Enable Cross-Domain Communication Between an IFrame and Its Parent Website?. For more information, please follow other related articles on the PHP Chinese website!