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
Release: 2024-11-28 19:11:11
Original
299 people have browsed it

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', '*');
Copy after login

Within the iframe, listen for the message event:

window.onmessage = function(e) {
    if (e.data == 'hello') {
        alert('It works!');
    }
};
Copy after login
Copy after login

Iframe to Parent Site:

In the iframe, send a message to the top-level parent window:

window.top.postMessage('hello', '*')
Copy after login

Within the parent window, listen for the message event:

window.onmessage = function(e) {
    if (e.data == 'hello') {
        alert('It works!');
    }
};
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template