我正在学习MessageChannel和transferable 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 缓冲区时——我在另一端没有收到任何数据:
但如果我尝试发送一些简单的东西,请说:
messageChannel.port1.postMessage('hello');
然后我看到:
使用可转移对象时——数据是否在其他地方表示?我似乎能够很好地传输端口,但我正在努力传输数据数组。但是,因为我的异常没有被抛出——看起来它被转移了......但它去哪儿了?