DEV Community

Alex Adam
Alex Adam

Posted on • Originally published at alexadam.dev

4 1

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs