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"
});
});
Is this an intended behaviour or maybe a bug in the chrome.storage API?