在内容脚本和背景页面之间传递的消息是JSON序列化的。
如果要
ArrayBuffer通过JSON序列化的通道传输对象,请在传输之前和之后将缓冲区包装在视图中。
我展示了一个孤立的示例,以便该解决方案通常适用,而不仅仅是您的情况。该示例显示了如何传递
ArrayBuffers和类型数组,但是该方法也可以通过使用API
应用于
File和
Blob对象
FileReader。
// In your case: self.data = { data: new Uint8Array(xhr.response), ...// Generic example:var example = new ArrayBuffer(10);var data = { // Create a view data: Array.apply(null, new Uint8Array(example)), contentType: 'x-an-example'};// Transport over a JSON-serialized channel. In your case: sendResponsevar transportData = JSON.stringify(data);//"{"data":[0,0,0,0,0,0,0,0,0,0],"contentType":"x-an-example"}"// At the receivers end. In your case: chrome.extension.onRequestvar receivedData = JSON.parse(transportData);// data.data is an Object, NOT an ArrayBuffer or Uint8ArrayreceivedData.data = new Uint8Array(receivedData.data).buffer;// Now, receivedData is the expected ArrayBuffer object此解决方案已在Chrome 18和Firefox中成功测试。
new Uint8Array(xhr.response)
用于创建的视图ArrayBuffer
,以便可以读取各个字节。Array.apply(null,<Uint8Array>)
用于使用Uint8Array
视图中的键创建普通数组。此步骤减小了序列化消息的大小。 警告:此方法仅适用于少量数据。 当类型化数组的大小超过125836时,将引发RangeError。如果需要处理大量数据,请使用其他方法在类型数组和纯数组之间进行转换。在接收者端,可以通过创建一个新
Uint8Array
缓冲区并读取buffer
属性来获得原始缓冲区。
在您的Google Chrome浏览器扩展程序中实施:
// Part of the Content script self.data = { data: Array.apply(null, new Uint8Array(xhr.response)), contentType: xhr.getResponseHeader('Content-Type') };...sendResponse({data: self.data});// Part of the background pagechrome.runtime.onMessage.addListener(function(data, sender, callback) { ... data.data = new Uint8Array(data.data).buffer;文献资料
- MDN:类型化数组
- MDN:
ArrayBuffer
- MDN:
Uint8Array
- MDN:
<Function> .apply
- Google Chrome扩展程序文档:消息传递>简单的一次性请求
“这使您可以分别 从内容脚本向扩展程序发送一次 JSON可序列化的消息 ,反之亦然”



