为什么html5 postMessage不适合我? [英] Why is html5 postMessage not working for me?

查看:265
本文介绍了为什么html5 postMessage不适合我?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用几行javascript来创建iframe元素,然后我想发送一条消息,如下所示:

I use a few lines of javascript to create an iframe element, and then I'd like to send it a message, like this:

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');
})

然后,在 http:// localhost:3000 / iframe.html (iframe的来源)是这样的:

And then, inside http://localhost:3000/iframe.html (the source of the iframe) is something like this:

<!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>

但没有任何反应......我甚至试图不使用原产地安全检查,但即便如此没有任何反应......就像从来没有得到消息...

But nothing happens... I even tried to not use the safety check for origin, but even like that nothing happens... Like it never got the message...

我是否遇到过某种异常问题?我试图确保在postMessage消失之前加载iframe ...

Am I in some kind of async problem ? I tried to make sure the iframe was loaded before the postMessage went away...

EDIT1:此外,控制台上没有显示错误......

Also, no errors show on the console...

EDIT2:我在谷歌Chrome 11和Firefox 4中试过它

I tried it in Google Chrome 11 and Firefox 4

提前谢谢。

推荐答案

有两个可能的问题:


  1. 你正在打电话<加载子框架之前code> callback - 在加载事件中尝试或在中执行此操作setTimeout

  2. 我从来没有设法获得 postMessage 来处理其他任何'*'作为起源。如果我在其中放置了一个URL,我会收到安全警告安全错误: http:// xxx / 的内容可能无法加载数据来自 http:// yyy / ,但仅在错误控制台(Ctrl + Shift + J)中,不在任何其他地方。我怀疑还有一些其他东西需要设置才能工作,但我还没弄清楚是什么。

  1. You're calling callback before the child frame has loaded - try it in the load event or do it in a setTimeout
  2. I've never managed to get postMessage to work with anything other that '*' as the origin. If I put a URL in there I get a security warning "Security Error: Content at http://xxx/ may not load data from http://yyy/", except only in the error console (Ctrl + Shift + J) not in any other place. I suspect there's some other stuff that needs set up somewhere for that to work, but I've not yet figured out what.

< a href =http://jsfiddle.net/robertc/Bh8jB/ =nofollow>这是一个jsfiddle ,你的代码稍微修改一下,加载了我的域名文档,适用于我的Firefox和Chrome。

Here's a jsfiddle with a slightly modified version of your code loading a document off my domain, works for me in Firefox and Chrome.

这篇关于为什么html5 postMessage不适合我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆