This guide explains the mechanics of how two browser windows can communicate using the postMessage API. We will use two example files: a "Sender" page that initiates the communication and a "Receiver" page that listens for it.

The Core Concept

The primary purpose of postMessage is to enable scripts in different windows (e.g., a main page and a popup, or a page and an iframe) to share information. This is especially important when the windows are from different origins (domains), as the browser's Same-Origin Policy would normally prevent them from interacting directly.


Part 1: The Sender Page

The Sender's role is to open the target window and dispatch a message to it. Let's break down the provided sender code.

Sender Code (start.html)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Start Page</title>
</head>
<body>

    <h1>Start Game</h1>
    <input type="button" value="Start" onclick="popup()">

    <script>

        var game_url = "<http://127.0.0.1:5501/case1>";
        
        

        function popup() {
            var gameWindow = window.open(game_url, "pop", "width=850,height=750,resizable=1");
            
            setTimeout(function() {
                const message = { "readyToPlay": true, "name": "Voorivex" };
             
                gameWindow.postMessage(JSON.stringify(message));
            }, 1000);
        }
    </script>
</body>
</html>

Functional Breakdown:

  1. Opening the Target Window:
  2. Delaying the Message:
  3. Sending the Message:

Part 2: The Receiver Page

The Receiver's role is to listen for incoming messages and act upon the data they contain. Let's break down the receiver code.

Receiver Code (The Popup)

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Some Site</title>

	<script>
		var postMessageHandler = function(e) {
		
			msg = JSON.parse(e.data)
			if (msg.readyToPlay){
				document.getElementById("fs").innerText = "Ready to showcase your SUDOKU skills Mr. " + msg.name;
				if (msg.url){
					window.open(msg.url)
				}
			}
		}
		window.addEventListener("message", postMessageHandler, false);
	</script>

</head>
<body>

<h2 id="fs">Game is loading...</h2>
<img src="Sudoku.png">

</body>
</html>

Functional Breakdown:

  1. Listening for Messages:
  2. Handling the Event: