简单的跨域iframe postMessage在jsfiddle中有效,但在本地无效

问题描述 投票:0回答:1

我正在尝试在另一个域上使用

iframe
,但我陷入了“Hello World!”舞台。

我有两个文件,通过两个静态服务器提供服务。我通过两个不同的域和不同的端口引用这些文件。

http://localhost:8080/index.html

<iframe id="target" src="http://hocallost:8081/iframe.html" frameborder="1"></iframe>

<script>
    var target = document.getElementById('target');
    target.contentWindow.postMessage('hello', '*');
</script>

http://localhost:8081/iframe.html

<script>
    window.addEventListener('message', function receiveMessage(message) {
        console.log(message);
        document.body.textContent = "Hello World!";
    }, false);
</script>

现在,在本地,消息事件处理程序甚至没有触发。我没有消息,console.log 没有被调用,我的断点也没有中断。

当我将

index.html
的源代码粘贴到 JSFiddle 中时,它就可以工作了!事件触发,我收到 Hello World。

现在,我显然无法在生产应用程序上依赖 JSFiddle,我做错了什么?我在这里缺少什么? JSFiddle 是否在幕后做了一些我没有做的事情?

javascript iframe
1个回答
1
投票

您似乎没有等待目标 iframe 加载。

var target = document.getElementById('target');
target.onload = function(){
    target.contentWindow.postMessage('hello', '*')
}

注意:部署代码时不要忘记将“*”替换为相关源。

© www.soinside.com 2019 - 2024. All rights reserved.