Home > Web Front-end > JS Tutorial > How Can I Enable Cross-Domain Communication Between an IFrame and Its Parent Website?

How Can I Enable Cross-Domain Communication Between an IFrame and Its Parent Website?

Barbara Streisand
Release: 2024-11-27 01:06:13
Original
360 people have browsed it

How Can I Enable Cross-Domain Communication Between an IFrame and Its Parent Website?

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

On the iframe side, an onmessage event can capture and process the message:

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

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

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!');
    }
};
Copy after login
Copy after login

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!

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