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

How Can Iframes on Different Domains Communicate Using PostMessage?

Barbara Streisand
Release: 2024-11-26 06:12:08
Original
390 people have browsed it

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

In the iframe:

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

Iframe to Parent Communication

In the parent window:

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

In the iframe:

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

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!

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