How to communicate between window and iframe?

Member

by aubrey , in category: Javascript , 10 days ago

How to communicate between window and iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , 9 days ago

@aubrey 

There are several ways to communicate between a window and an iframe:

  1. PostMessage API: The postMessage API allows for safe cross-origin communication between a window and an iframe. You can use the postMessage method to send messages and the window.addEventListener method to listen for messages.


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"
});


  1. Window Proxy: You can create a proxy object in the parent window and pass it to the iframe. This proxy object can be used to call methods or set properties in the 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');


  1. Custom Events: You can also use custom events to communicate between a window and an iframe. You can dispatch a custom event in one window and listen for that event in the other window.


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.