2

Per Mathias Bynens highly upvoted answer to "Sort JavaScript object by key", string keys in JS objects will be sorted in the order in which they were entered, eg when retrieved by Object.keys(). This indeed also happens when I try it in an ordinary fashion. However, when using a string-key object as parameter key in the Chrome extension API call chrome.storage.sync.get(key,function(retrieved_data){}), the result, in my hands, is an object where the keys obtained by Object.keys() are sorted alphabetically and not in the order they were entered.

I use the key parameter to store default values (most often for option settings in an extension) which can be used as a fallback when the extension fails to retrieve any data from storage (typically the first time an extension is used). The example below shows the difference in behaviour.


manifest.json:

{
  "manifest_version": 2, 
  "name": "demo extension",
  "version": "0.1",
  "description": "debugging tool",
   "permissions":[
    "storage"
  ],
 "content_scripts": [{
       "css": ["styles.css"], 
      "js": ["jquery.js","content.js"],
    "matches": ["https://*.google.com/*"]
  }]
}

styles.css:

.myTxt{height:100px;,width:150px;}

content.js (jQuery also required):

jQuery(function($){
  var keys;
  var fallbackObject = {z:"first",a:"last"};
  $(document).ready(function(){
    $("body").prepend(`<textarea id="myTxt1" class="myTxt"></textarea><textarea id="myTxt2" class="myTxt"></textarea>`);
    
    //===== alternative 1:  ============
    //fallbackObject is used "normally"
    keys = Object.keys(fallbackObject);
    $("#myTxt1").val("Alternative 1, without chrome.storage.sync.get(): " + keys);
    //result : "z,a"
    
    //===== alternative 2:  ============
    //fallbackObject is used as a default parameter in chrome.storage.sync.get();
    
    chrome.storage.sync.get({storageObject:fallbackObject},function(message){
      keys = Object.keys(message.storageObject);
      $("#myTxt2").val("Alternative 2, with chrome.storage.sync.get(): " + keys);
    });
    //result:"a,z"
 });
});

result:

result of demo code

Is this an intended behaviour or maybe a bug in the chrome.storage API?

danbae
  • 319
  • 1
  • 5
  • 18
  • Maybe Chrome's storage does not use JS Objects nor JSON internally, in which case, this order can be lost in the process of storing values, and getting them back – blex Jul 04 '20 at 19:51
  • Storage is using JSON schema so it doesn't guarantee the order of object keys. – wOxxOm Jul 04 '20 at 20:55
  • Would that be true regardless of StorageArea, ie also for `chrome.storage.local`? Either way, I think it certainly would be an improvement if key order could be preserved also in this context. I solved the problem by using an array of objects instead to make sure the order is unchanged. – danbae Jul 04 '20 at 21:55

0 Answers0