我使用几行javascript来创建一个iframe元素,然后我想给它发一条消息,如下所示:
function loadiframe (callback) {
var body = document.getElementsByTagName('body')[0];
var iframe = document.createElement('iframe');
iframe.id = 'iframe';
iframe.seamless = 'seamless';
iframe.src = 'http://localhost:3000/iframe.html';
body.appendChild(iframe);
callback();
}
loadiframe(function() {
cpframe = document.getElementById('iframe').contentWindow;
cpframe.postMessage('please get this message','http://localhost:3000');
console.log('posted');
})
Run Code Online (Sandbox Code Playgroud)
然后,在http:// localhost:3000/iframe.html(iframe的源代码)里面是这样的:
<!DOCTYPE html>
<html>
<head>
<title>does not work</title>
<script>
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
if (event.origin == "http://localhost:3000") {
document.write(JSON.stringify(event));
document.write(typeof event);
}
}
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
但没有任何反应......我甚至试图不使用原产地的安全检查,但即使没有发生任何事情......就像从来没有得到消息......
我在某种异常问题吗?我试图确保在postMessage消失之前加载了iframe ...
EDIT1:此外,控制台上没有显示错误......
EDIT2:我在Google Chrome 11和Firefox 4中尝试过它
先感谢您.
有两个可能的问题:
callback您在子框架加载之前调用- 在load事件中尝试或在setTimeoutpostMessage以“*”作为起源的任何其他东西。如果我在其中输入 URL,则会收到安全警告“安全错误:http://xxx/上的内容可能无法从http://yyy/加载数据”,除非仅在错误控制台中 (Ctrl + Shift + J)不在任何其他地方。我怀疑还需要在某个地方设置一些其他东西才能发挥作用,但我还没有弄清楚是什么。这是一个 jsfiddle,其中代码略有修改,可从我的域加载文档,适用于 Firefox 和 Chrome。
| 归档时间: |
|
| 查看次数: |
10899 次 |
| 最近记录: |