2014-10-02 399 views
0

我想在主窗口和页面中加载的iframe之间进行通信。我过去做过这件事(代码仍然有效),但是我不能在另一个项目中使用它。我创建了一个例子来重现这个问题。它有一个基本的服务器端(仅供应一些文件)使用Le Statique module使用postMessage时“消息”事件未被触发

最重要的部分是客户端,但让我们先从服务器:

服务器(的NodeJS)

创建两个服务器(在8000一个聆听和另一个监听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> 
... 

然而,从IFRAME "message"事件不会被解雇。为什么?

我在控制台中看不到任何错误。

回答

1

iframe窗口未完全加载(没有人收听"message"事件)。

通过监听iframe的负载情况下,我们相信,一切都被加载,我们可以发出事件:

iframe.onload = function() { 
    iframe.contentWindow.postMessage("hi", "*"); 
};