我正在尝试与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://hocallost: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是否在幕后做一些我做不到的事情?
您似乎不必等待目标iframe的加载。
var target = document.getElementById('target');
target.onload = function(){
target.contentWindow.postMessage('hello', '*')
}
注意:部署代码时,请不要忘记用相关的原点替换'*'。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句