chrome.storage.local strange behaviour: confused by a duplicate object

后端 未结 1 1854
庸人自扰
庸人自扰 2021-01-21 18:07

After a lot of bug-hunting, I managed to narrow my problem down to this bit of code:

dup = {a: [1]}
chrome.storage.local.set({x: [dup, dup]});
chrome.storage.loc         


        
相关标签:
1条回答
  • 2021-01-21 18:20
    1. No it is not intentional and should be reported as a bug: https://crbug.com/606955 (and now it is fixed as of Chrome 52!).
    2. As I explained in the bug report, the cause of the bug is that the objects are identical. If your object dup only contains simple values (i.e. no nested arrays or objects, only primitive values such as strings, numbers, booleans, null, ...), then a shallow clone of the object is sufficient:

      dup = {a: [1]}
      dup2 = Object.assign({}, dup);
      chrome.storage.local.set({x: [dup, dup2]});
      

      If you need support for nested objects, then you have to make a deep clone. There are many existing libraries or code snippets for that, so I won't repeat it here. A simple way to prepare values for chrome.storage is by serializing it to JSON and then parsing it again (then all objects are unique).

      dup = {a: [1]}
      var valueToSave = JSON.parse(JSON.stringify([dup, dup]));
      chrome.storage.local.set({x: valueToSave});
      
      // Or:
      var valueToSave = [ dup, JSON.parse(JSON.stringify(dup)) ];
      chrome.storage.local.set({x: valueToSave});
      
    0 讨论(0)
提交回复
热议问题