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 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.
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>
window.open(game_url, ...) is called when the button is clicked.game_url.gameWindow variable. This reference is essential for directing the message.setTimeout(function() { ... }, 1000); is used to create a 1-second delay.setTimeout, the postMessage method is called on the gameWindow reference.gameWindow.postMessage(JSON.stringify(message), target_origin);message is created. It must be converted into a string before sending, which is done using JSON.stringify().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>
window.addEventListener("message", postMessageHandler, false); is the core of the receiver.postMessageHandler function to be executed automatically whenever a message event is dispatched to this window.postMessageHandler function is called, and an event object is passed to it as an argument.e.data property of this object contains the stringified message sent from the sender.