使用可传输对象调用postMessage时,MessageChannel port.postMessage的数据为空?

时间:2014-01-14 06:23:31

标签: javascript iframe transferable

我正在了解MessageChanneltransferable objects

我的页面中有一个跨域的iframe。 MessageChannel周围的文档表明它完全支持跨域通信。

我在iframe中的跨域页面中有这段代码:

var messageChannel = new MessageChannel();

//  Transfer port2 to the background page to establish communications.
window.parent.postMessage('connect', 'chrome-extension://jbnkffmindojffecdhbbmekbmkkfpmjd', [messageChannel.port2]);
messageChannel.port1.start();

// Give time for background to setup its port. Not great practice, but OK for example.
setTimeout(function(){ 

    // Create a 32MB "file" and fill it.
    var uInt8Array = new Uint8Array(1024*1024*32); // 32MB
    for (var i = 0; i < uInt8Array.length; ++i) {
        uInt8Array[i] = i;
    }

    messageChannel.port1.onmessage = function(message){
        console.log('iframe message:', message);
    };

    messageChannel.port1.postMessage(uInt8Array.buffer, [uInt8Array.buffer]);

    if (uInt8Array.buffer.byteLength)
        throw "Failed to transfer buffer";

}, 1000);

在我的背景页面中我有:

window.onmessage = function(messageEvent) {
    //  Make sure the origin is correct for security
    if (messageEvent.origin === 'https://www.youtube.com') {

        if (messageEvent.ports.length > 0 && messageEvent.data === 'connect') {
            var port = messageEvent.ports[0];

            port.onmessage = function (message) {
                console.log("background message:", message);
            };
        }

    }
};

当我尝试postMessage uInt8Array缓冲区时 - 我没有收到另一方的数据:

enter image description here

但如果我尝试发送简单的信息,请说:

messageChannel.port1.postMessage('hello');

然后我看到了:

enter image description here

使用可转移对象时 - 数据是否代表其他地方?我似乎能够很好地传输端口,但我正在努力转移数据数组。但是,因为我的异常没有被抛出 - 看起来它被转移了...但是它去了哪里?

1 个答案:

答案 0 :(得分:4)

我已经减少了您的代码示例,并发现ArrayBufferMessagePort传递MessageChannel时总是丢失。

报告为问题334408:“在postMessage期间,MessageCuffer在MessageChannel中丢失(接收者的event.data == null)” https://code.google.com/p/chromium/issues/detail?id=334408