I want to communicate between the main window and an iframe that is loaded in page. I did this thing in the past (the code still works), but however I cannot use it in another project. I create an example to reproduce the issue. It has a basic server side (that just serves some files) using Le Statique module.
The most important part is the client side, but let's start with the server:
Creates two servers (one listening on 8000 and another one listening on 9000).
// Dependencies
var Statique = require("statique")
, Http = require('http')
;
Http.createServer(new Statique({
root: __dirname + "/receiver"
}).setRoutes({
"/": "/html/index.html"
}).serve).listen(8000);
Http.createServer(new Statique({
root: __dirname + "/sender"
}).setRoutes({
"/": "/html/index.html"
}).serve).listen(9000);
...
window.onload = function () {
addEventListener("message", function (e) {
// This part is never fired!
console.log("2", e.data);
}, false);
};
...
...
<body>
<iframe src="http://localhost:8000" frameborder="0" id="iframe"></iframe>
<script>
iframe.contentWindow.postMessage("hi", "*");
</script>
</body>
...
However, "message" events from iframe are not fired. Why?
I don't see any error in console.
The iframe window is not completely loaded (nobody listens for "message" events).
By listening for iframe load event we are sure that everything was loaded and we can emit the event:
iframe.onload = function () {
iframe.contentWindow.postMessage("hi", "*");
};