DEV Community

Alex Adam
Alex Adam

Posted on • Originally published at alexadam.dev

How to communicate between an iframe and the parent page

From parent page -> iframe

In the parent page:

const iframe = document.getElementById('iframe');
iframe.contentWindow.postMessage('some message', '*');
Enter fullscreen mode Exit fullscreen mode

In the iframe:

window.onmessage = function(e) {
  if (e.data === 'some message') {
    alert('It works!');
  }
};
Enter fullscreen mode Exit fullscreen mode

From iframe -> parent page

In the parent page:

window.onmessage = function(e) {
  if (e.data === 'from iframe') {
    alert('It works!');
  }
};
Enter fullscreen mode Exit fullscreen mode

In the iframe:

window.top.postMessage('from iframe', '*')
Enter fullscreen mode Exit fullscreen mode

Source

Top comments (0)