Home >Web Front-end >JS Tutorial >How Can I Enable Cross-Domain Communication Between an Iframe and its Parent Site?

How Can I Enable Cross-Domain Communication Between an Iframe and its Parent Site?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 19:11:11385browse

How Can I Enable Cross-Domain Communication Between an Iframe and its Parent Site?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn