提问人:Madara's Ghost 提问时间:1/6/2015 更新时间:1/6/2015 访问量:1248
简单的跨域 iframe postMessage 在 jsfiddle 中有效,但不能在本地工作
Simple cross-domain iframe postMessage works in jsfiddle but not locally
问:
我正在尝试在另一个域上工作,但我卡在了“Hello World!”阶段。iframe
我有两个文件,通过两个静态服务器提供服务。我通过两个不同的域和不同的端口引用这些文件。
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://hocallost:8081/iframe.html
<script>
window.addEventListener('message', function receiveMessage(message) {
console.log(message);
document.body.textContent = "Hello World!";
}, false);
</script>
现在,在本地,消息事件处理程序甚至没有触发。我没有消息,控制台 .log 未调用,我的断点未中断。
当我获取源代码并将其粘贴到 JSFiddle 中时,它可以工作!事件触发,我得到 Hello World。index.html
现在,我显然无法在我的生产应用程序上依赖 JSFiddle,我做错了什么?我在这里错过了什么?JSFiddle 在幕后做了一些我没有做的事情吗?
答:
1赞
Denys Séguret
1/6/2015
#1
您似乎没有等待目标 iframe 被加载。
var target = document.getElementById('target');
target.onload = function(){
target.contentWindow.postMessage('hello', '*')
}
注意:在部署代码时,不要忘记将“*”替换为相关源。
评论