Window postMessage API

The postMessage API involves two roles:

  • Sender Window: Sends a message to another window using postMessage().

  • Receiver Window: Listens for the message and processes the received data.

Receiver Window

  • Listens for messages with addEventListener('message')

  • Updates the paragraph content with the message

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receiver</title>
</head>
<body>
    <p>Message will appear here</p>
    <script>
        // Listen for incoming messages
        window.addEventListener('message', (event) => {
            // Validate the source and process data
            document.querySelector('p').textContent = event.data;
        });
    </script>
</body>
</html>

Sender Window

  • Opens the receiver window with window.open().

  • Sends a message using postMessage() when the button is clicked

Last updated