@aubrey
There are several ways to communicate between a window and an iframe:
Example: In the parent window:
1 2 |
const iframe = document.getElementById('myIframe'); iframe.contentWindow.postMessage('Hello from parent window', '*'); |
In the iframe:
1 2 3 |
window.addEventListener('message', function(event) { console.log(event.data); // "Hello from parent window" }); |
Example: In the parent window:
1 2 3 4 5 6 7 |
const proxy = { sendMessage(message) { console.log(message); } }; const iframe = document.getElementById('myIframe'); iframe.contentWindow.proxy = proxy; |
In the iframe:
1
|
window.parent.proxy.sendMessage('Hello from iframe'); |
Example: In the parent window:
1 2 3 |
const iframe = document.getElementById('myIframe'); const event = new CustomEvent('sendMessage', { detail: 'Hello from parent window' }); iframe.contentWindow.dispatchEvent(event); |
In the iframe:
1 2 3 |
window.parent.addEventListener('sendMessage', function(event) { console.log(event.detail); // "Hello from parent window" }); |
By using one of these methods, you can effectively communicate between a window and an iframe.