gpt4 book ai didi

javascript - "message"使用 postMessage 时未触发事件

转载 作者:行者123 更新时间:2023-12-03 11:43:25 27 4
gpt4 key购买 nike

我想在主窗口和页面中加载的 iframe 之间进行通信。我过去做过这件事(代码仍然有效),但是我不能在另一个项目中使用它。我创建了一个示例来重现该问题。它有一个基本的服务器端(仅提供一些文件),使用 <sub>Le</sub> Statique module .

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

服务器(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>
...

但是,"message"来自 iframe 的事件不会被触发。为什么?

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

最佳答案

iframe 窗口未完全加载(没有人监听“message” 事件)。

通过监听 iframe 加载事件,我们确信所有内容都已加载,并且我们可以发出该事件:

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

关于javascript - "message"使用 postMessage 时未触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26165272/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com