简体   繁体   English

将内容脚本中的大型JSON / JS对象压缩为background.js-Chrome扩展

[英]Compress large JSON/JS object from content script to background.js - chrome extension

I want to send a large JSON/JS object from content.js to background.js 我想将一个大型JSON / JS对象从content.js发送到background.js

I have tried the library lz-string to compress the object. 我尝试了库lz-string来压缩对象。

content.js content.js

var compressedJSON = LZString.compress(JSON.stringify(largeObject));
chrome.runtime.sendMessage({type: "type1", result: compressedJSON}, function(response){
  // handle response
});

background.js background.js

var uncompressedJSON = JSON.parse(LZString.decompress(request.result));

Doing so, I get null for uncompressedJSON in background.js 这样做,background.js中的uncompressedJSONnull

However, if I decompress the same string compressedJSON in content.js using LZString.decompress() , it works! 但是,如果我使用LZString.decompress()在content.js中解压缩相同的字符串compressedJSON ,它就可以工作!

I wonder if UTF encoding has something to do with this. 我想知道UTF编码是否与此有关。 This library seems to work really well as I am able to compress my object by about 78%. 该库似乎工作得很好,因为我能够将对象压缩约78%。

Suggestions for other libraries are welcome too! 也欢迎其他图书馆提出建议!

Use LZString.compressToUTF16 and LZString.decompressFromUTF16 : 使用LZString.compressToUTF16LZString.decompressFromUTF16

compressToUTF16 produces "valid" UTF-16 strings in the sense that all browsers can store them safely. 从所有浏览器都可以安全存储的意义上来说,compressToUTF16会生成“有效的” UTF-16字符串。 So they can be stored in localStorage on all browsers tested (IE9-10, Firefox, Android, Chrome, Safari). 因此它们可以存储在所有经过测试的浏览器(IE9-10,Firefox,Android,Chrome,Safari)上的localStorage中。 Can be decompressed with decompressFromUTF16. 可以使用decompressFromUTF16解压缩。 This works by using only 15bits of storage per character. 每个字符仅使用15位存储空间即可工作。 The strings produced are therefore 6.66% bigger than those produced by compress 因此,产生的琴弦比通过压缩产生的琴弦大6.66%

However, it'd be still much much faster to send an uncompressed JSON.stringify result in 32MB string chunks (along with chunk number), then combine them in the background script. 但是,以32MB的字符串块(以及块号)发送未压缩的JSON.stringify结果,然后将它们组合到后台脚本中,仍然要快得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM