javascript - window.postmessage - event.data始终为null

Has*_*ken 4 javascript iframe firefox postmessage

我有一个iframe,并希望将数据从iframe发送到父窗口.

在iframe的js代码中,我有以下语句

window.parent.postMessage('hello', '*');
Run Code Online (Sandbox Code Playgroud)

父窗口中的相应消息处理程序如下所示

$(window).bind('message', function (event) {
    console.log(event.data);
    console.log(event.origin);
    console.log(event.source);
    console.log('received');
});
Run Code Online (Sandbox Code Playgroud)

我从localhost加载代码,iframe源也从localhost加载.我在firefox 21中运行代码.

问题是,event.data永远是nullevent.orign and event.sourceundefined.我该如何解决这个问题?

voi*_*ski 8

请参阅FrédéricHamidi的答案.发生了什么是jQuery将原始事件封装在适当的jQuery.event对象类型中.因此,要获得原始事件,您只需:

$(window).on("message", function(e) {
  console.log("Orignal:", e.originalEvent);
});
Run Code Online (Sandbox Code Playgroud)


har*_*rsh 7

window.parent.postMessage('hello', '*');   
window.addEventListener("message", receiveMessage, false);
       function receiveMessage (event) {
            console.log(event.data);
            console.log(event.origin);
            console.log(event.source);
            console.log('received');
        }
Run Code Online (Sandbox Code Playgroud)

这将按预期工作; 也许在事件绑定("消息")中存在问题,jQuery会在获取内容时更新.