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
Barbara StreisandOriginal
2024-11-27 01:06:13367browse

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

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!

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