Home ยป HTML5 Web Messaging Tutorial

HTML5 Web Messaging Tutorial

by shedders

Web Messaging in HTML5 allows communication between browser contexts such as iframes, tabs, windows, or workers. It enables secure and efficient messaging between these contexts, overcoming the limitations of the Same-Origin Policy.

In this tutorial, you’ll learn:

  1. What is Web Messaging?
  2. Using postMessage for communication.
  3. Sending messages between iframes and windows.
  4. Using Web Messaging with Web Workers.
  5. Practical examples and best practices.

1. What is Web Messaging?

Web Messaging provides APIs for communication:

  • postMessage API: Sends messages between windows, iframes, or other contexts.
  • Message Events: Listen for and handle incoming messages.

Key Features:

  • Cross-Origin Communication: Securely exchange messages between origins.
  • Asynchronous: Messages are exchanged asynchronously.
  • Secure: You can verify the origin of the message.

2. Using postMessage for Communication

Example 1: Basic Communication Between Parent and Child

Step 1: Parent Window (HTML)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Parent Window</title>
</head>
<body>
    <h1>Parent Window</h1>
    <button id="sendMessage">Send Message to Child</button>
    <iframe id="childFrame" src="child.html" style="width: 100%; height: 300px;"></iframe>

    <script>
        const iframe = document.getElementById("childFrame");
        const sendMessageButton = document.getElementById("sendMessage");

        sendMessageButton.addEventListener("click", () => {
            iframe.contentWindow.postMessage("Hello from Parent!", "*");
        });

        // Listen for messages from the child
        window.addEventListener("message", (event) => {
            console.log("Message from Child:", event.data);
        });
    </script>
</body>
</html>

Step 2: Child Window (child.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Child Window</title>
</head>
<body>
    <h1>Child Window</h1>
    <p>Listening for messages from the parent...</p>

    <script>
        // Listen for messages from the parent
        window.addEventListener("message", (event) => {
            console.log("Message from Parent:", event.data);

            // Send a response back to the parent
            event.source.postMessage("Hello from Child!", event.origin);
        });
    </script>
</body>
</html>

Explanation:

  • postMessage(message, targetOrigin): Sends a message to the specified target.
  • message: The data to send.
  • targetOrigin: The expected origin of the target window for security.
  • message event: Handles incoming messages.

3. Sending Messages Between Tabs

Example 2: Communicating Between Browser Tabs

Step 1: Sender Tab

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sender Tab</title>
</head>
<body>
    <h1>Sender Tab</h1>
    <button id="sendMessage">Send Message to Receiver</button>

    <script>
        const receiverUrl = "receiver.html";
        const receiverTab = window.open(receiverUrl, "_blank");

        document.getElementById("sendMessage").addEventListener("click", () => {
            receiverTab.postMessage("Hello from Sender Tab!", "*");
        });
    </script>
</body>
</html>

Step 2: Receiver Tab (receiver.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Receiver Tab</title>
</head>
<body>
    <h1>Receiver Tab</h1>
    <p>Listening for messages from the sender tab...</p>

    <script>
        window.addEventListener("message", (event) => {
            console.log("Message from Sender Tab:", event.data);
        });
    </script>
</body>
</html>

4. Web Messaging with Web Workers

Web Workers can exchange messages with the main thread using postMessage.

Example 3: Main Thread and Worker Communication

Step 1: Worker Script (worker.js)

// worker.js
self.onmessage = function (event) {
    console.log("Message from Main Thread:", event.data);
    const result = `Processed: ${event.data}`;
    self.postMessage(result);
};

Step 2: Main Thread (HTML)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Web Worker Messaging</title>
</head>
<body>
    <h1>Web Worker Messaging</h1>
    <button id="sendToWorker">Send to Worker</button>
    <p id="output">Result: </p>

    <script>
        const worker = new Worker("worker.js");
        const output = document.getElementById("output");

        document.getElementById("sendToWorker").addEventListener("click", () => {
            worker.postMessage("Hello Worker!");
        });

        worker.onmessage = function (event) {
            output.textContent = `Result: ${event.data}`;
        };
    </script>
</body>
</html>

Explanation:

  • worker.postMessage(data): Sends data to the worker.
  • self.onmessage: Listens for messages in the worker.
  • self.postMessage(data): Sends data back to the main thread.

5. Practical Application: Cross-Origin Messaging

You can securely communicate between two origins using the postMessage API.

Example 4: Secure Cross-Origin Communication

Step 1: Parent Window

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Secure Parent</title>
</head>
<body>
    <h1>Secure Parent</h1>
    <button id="sendMessage">Send Secure Message</button>
    <iframe id="childFrame" src="https://example.com/child.html" style="width: 100%; height: 300px;"></iframe>

    <script>
        const iframe = document.getElementById("childFrame");

        document.getElementById("sendMessage").addEventListener("click", () => {
            iframe.contentWindow.postMessage("Secure message from Parent", "https://example.com");
        });

        window.addEventListener("message", (event) => {
            if (event.origin !== "https://example.com") {
                console.warn("Origin not trusted:", event.origin);
                return;
            }
            console.log("Message from Child:", event.data);
        });
    </script>
</body>
</html>

Step 2: Child Window (https://example.com/child.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Secure Child</title>
</head>
<body>
    <h1>Secure Child</h1>
    <p>Listening for secure messages...</p>

    <script>
        window.addEventListener("message", (event) => {
            if (event.origin !== "https://trustedparent.com") {
                console.warn("Untrusted origin:", event.origin);
                return;
            }

            console.log("Message from Parent:", event.data);

            // Send a secure response
            event.source.postMessage("Secure response from Child", event.origin);
        });
    </script>
</body>
</html>

Explanation:

  • Always verify the origin of incoming messages to ensure secure communication.
  • Use specific target origins instead of “*” in postMessage.

6. Best Practices

  1. Verify Origins: Always check the origin of the message.
  2. Use Secure Connections: Use HTTPS to prevent man-in-the-middle attacks.
  3. Avoid Global Handlers: Use scoped listeners where possible.
  4. Sanitize Messages: Avoid injecting untrusted data into the DOM.

7. Browser Support

Browser Support
Google Chrome Yes
Firefox Yes
Safari Yes
Microsoft Edge Yes
Internet Explorer Partial

8. Conclusion

In this tutorial, you learned:

  1. How to use postMessage for Web Messaging.
  2. Communication between iframes, windows, and tabs.
  3. How to securely exchange messages across origins.
  4. Using Web Messaging with Web Workers.

Web Messaging is a powerful tool for creating interactive and secure web applications.

 

You may also like