Home  >  Article  >  Web Front-end  >  How Can Iframes on Different Domains Communicate Using PostMessage?

How Can Iframes on Different Domains Communicate Using PostMessage?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 06:12:08316browse

How Can Iframes on Different Domains Communicate Using PostMessage?

Cross-Domain Communication between Iframe and Parent Site

When an iframe resides on a different domain than its parent site, direct communication through methods or content document access is not feasible. In such cases, the solution lies in cross-document messaging.

Parent to Iframe Communication

In the parent window:

myIframe.contentWindow.postMessage('hello', '*');

In the iframe:

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

Iframe to Parent Communication

In the parent window:

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

In the iframe:

window.top.postMessage('hello', '*')

Remember, the asterisk (*) in the postMessage() function represents wildcard, allowing the message to be received by any origin.

The above is the detailed content of How Can Iframes on Different Domains Communicate Using PostMessage?. 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