I know the basic usage of postMessage https://developer.mozilla.org/fr/docs/Web/API/Window/postMessage when you want to send data to the parent window from an iframe. But is it possible to make this more generic? for example, if in my iframe I publish with postMessage on the window object of my iframe, what could prevent the main window to add an event listener on the messages of the iframe. Here is an example :
in a directory tree that look like this:
root
|___ frontpage
| |____index.html
|___ iframe
|____index.html
the iframe/index.html
<!DOCTYPE html>
<html>
<head>
<title>iframe</title>
<meta charset="utf-8" />
<script>
const trustedOrigins = ["http://localhost:5001"];
function sendMsg(msg) {
console.log(`Send message iframe window`, msg);
window.postMessage(msg, trustedOrigins[0]);
}
setInterval(() => { sendMsg("Coucou") }, 5000);
</script>
</head>
<body>
<h1>Iframe body</h1>
</body>
</html>
the main page that embed the iframe : frontpage/index.html
<!DOCTYPE html>
<html>
<head>
<title>main</title>
</head>
<body>
<iframe src="http://localhost:5001/index.html"></iframe>
<script>
const trustedOrigins = ["http://localhost:5001"];
function onMsg(msg) {
console.log(`Message from an iframe`, msg);
}
const iframe = document.querySelector("iframe");
iframe.onload = () => {
console.log('Adding event listener on the iframe to catch its messages');
iframe.contentWindow.addEventListener("message", onMsg, false);
};
</script>
</body>
</html>
I expected to be able to display the messages that the iframe send to itself be nothing is displayed
install http-server to test it npm install -g http-server
cd frontpage
http-server -p 5000
cd iframe
http-server -p 5001
go with a browser to http://localhost:5000 and look at the console messages, the iframe send its messages but the event listener catch any of it.
Why ?
window.addEventListener("message", function(event) { console.log(event); }, false);