使用可传输对象调用postMessage时,MessageChannel port.postMessage的数据是否为空? [英] MessageChannel port.postMessage's data is null when calling postMessage with a transferable object?

查看:380
本文介绍了使用可传输对象调用postMessage时,MessageChannel port.postMessage的数据是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在了解


I'm learning about MessageChannel and transferable objects.

I've got an iframe which is cross-domain from my page. The documentation surrounding MessageChannel indicates that it fully supports cross-domain communications.

I've got this code inside of my cross-domain page inside of an 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);

and in my background page I have:

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

    }
};

When I attempt to postMessage the uInt8Array buffer -- I receive no data on the other side:

but if I try and send something simple, say:

messageChannel.port1.postMessage('hello');

then I see:

When using transferable objects -- is the data represented somewhere else? I seem to be able to transfer the port just fine, but I'm struggling to transfer the array of data. BUT, since my exception isn't being thrown -- it looks like it IS transferred... but where did it go??

解决方案

I've reduced your code sample and discovered that the ArrayBuffer is always lost when it is passed through a MessagePort of a MessageChannel.

Reported as issue 334408: "ArrayBuffer is lost in MessageChannel during postMessage (receiver's event.data == null)" https://code.google.com/p/chromium/issues/detail?id=334408

这篇关于使用可传输对象调用postMessage时,MessageChannel port.postMessage的数据是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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