栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Chrome扩展程序:如何将ArrayBuffer或Blob从内容脚本传递到后台而不丢失其类型?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Chrome扩展程序:如何将ArrayBuffer或Blob从内容脚本传递到后台而不丢失其类型?

在内容脚本和背景页面之间传递的消息是JSON序列化的。

如果要

ArrayBuffer
通过JSON序列化的通道传输对象,请在传输之前和之后将缓冲区包装在视图中。

我展示了一个孤立的示例,以便该解决方案通常适用,而不仅仅是您的情况。该示例显示了如何传递

ArrayBuffer
s和类型数组,但是该方法也可以通过使用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可序列化的消息 ,反之亦然”


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/374020.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号