Skip to content

postMessage

postMessage

A secure way to enable communication between two windows (or tabs) that belong to different origins (domains). Can pass JSON data oneway between origin1 and origin2

Note

The receiver must check the origin and source before interacting with the message

Note

Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy are needed SharedArrayBuffer objects

Basic Example

Open a new window and send a message to the other origin

origin1.html:

<!DOCTYPE html>
<html>
<head>
  <title>Origin 1</title>
</head>
<body>
  <button onclick="sendMessage()">Send Message</button>

  <script>
	function sendMessage() {
	  const otherWindow = window.open('https://origin2.com/origin2.html');
	  const message = 'Hello from Origin 1!';
	  const targetOrigin = 'https://origin2.com';
	  otherWindow.postMessage(message, targetOrigin);
	}
  </script>
</body>
</html>

origin2.html:

<!DOCTYPE html>
<html>
<head>
  <title>Origin 2</title>
</head>
<body>
  <script>
	window.addEventListener('message', receiveMessage, false);

	function receiveMessage(event) {
	  if (event.origin === 'https://origin1.com') {
		alert('Received message: ' + event.data);
	  }
	}
  </script>
</body>
</html>

IFrame Example

Parent.html:

<!DOCTYPE html>
<html>
<head>
  <title>Parent Window</title>
</head>
<body>
  <iframe src="https://origin2.com/child.html"></iframe>
</body>
</html>

Parent.html:

<!DOCTYPE html>
<html>
<head>
  <title>Child Window</title>
</head>
<body>
  <button onclick="sendMessage()">Send Message to Parent</button>

  <script>
	function sendMessage() {
	  const message = 'Hello from Child Window!';
	  parent.postMessage(message, 'https://origin1.com');
	}
  </script>
</body>
</html>

Security

https://book.hacktricks.xyz/pentesting-web/postmessage-vulnerabilities