I was trying to understand how to use the chrome.storage.api.
I have included the following in my manifest.json
:
"permissions": [
"activeTab","storage"
],
Than, I opened a new tab with the devtools and switched the <page context>
to the one of my chrome-extension. Than I typed:
chrome.storage.sync.set({"foo":"bar"},function(){ console.log("saved ok"); } );
and got:
undefined
saved ok
Than I tried getting this stored value:
chrome.storage.sync.get("foo",function(data){ console.log(data); } );
but this got me:
undefined
Object {}
Than I did the same, but instead of sync
I used local
and this worked as expected:
chrome.storage.local.set({"foo":"bar"},function(){ console.log("saved ok"); } );
..and the retrieval:
chrome.storage.local.get("foo",function(data){ console.log(data); } );
Which got me: Object {foo: "bar"}
as it should.
Is this because I am not signed in to my account on chrome? But in that case, isn't chrome.storage.sync
designed to fallback into storing the data locally?
EDIT
Strangely, when i type this straight on console it seems to be working, but this code doesn't run from background.js code inside a click listener:
var dataCache = {};
function addStarredPost(post)
{
var id = getPostId(post);
var timeStamp = new Date().getTime();
var user = getUserName();
dataCache[id] = {"id":id,"post":post,"time":timeStamp,"user":user};
chrome.storage.sync.set(dataCache,function(){ console.log("Starred!");});
}
After this is ran, chrome.storage.sync.get(null,function(data){ console.log(data); });
returns an empty object as if the data wasn't stored. :/
This code seems to be working perfect with chrome.storage.local
instead.
chrome.runtime.lastErros
returns undefined
Whoops!
The problem was I was trying to sync data that exceeded in size. (4096 Bytes per item)
I wasn't getting
chrome.runtime.lastError
because I was mistakenly putting it inside theget
function scope, instead of theset
function which was producing the error. Hence, I'm posting this answer so it might help others who share the same confusion.You should check
chrome.runtime.lastError
inside each api call, like so:This ran OK with
chrome.storage.local
because according to the docs you only have this limitation withsync
.printing
chrome.runtime.lastError
gave me:Object {message: "QUOTA_BYTES_PER_ITEM quota exceeded"}
The max size for chrome local storage is 5,242,880 bytes. To extend the storage you can add on the manifest.json :
The max size for chrome sync storage is:
(source)