MDN self-hosted library · e01.org

Window: message event

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
const targetFrame = window.top.frames[1];
const targetOrigin = "https://example.org";
const windowMessageButton = document.querySelector("#window-message");

windowMessageButton.addEventListener("click", () => {
  targetFrame.postMessage("hello there", targetOrigin);
});
js
window.addEventListener("message", (event) => {
  console.log(`Received message: ${event.data}`);
});
js
window.onmessage = (event) => {
  console.log(`Received message: ${event.data}`);
};