7

I have a little snippet working with LocalStorage but I cannot make it work on Chrome Storage scheme yet.

When my application starts I check a variable in localStorage

var bookNarration=parseInt(localStorage.getItem("narration")); 

If that variable is undefined, it means that my app has been opened for the first time and I after handle bookLanguage in a switch using the "default" declaration.

switch(window.bookNarration) { case 2: window.narrationShift = window.spanishShift; break; case 3: window.narrationShift = window.frenchShift; break; case 10: window.narrationShift = window.neutralShift; break; default: window.narrationShift = 0; } 

To make it work with Chrome Storage I change my code on this way:

var bookNarration=parseInt(chrome.storage.local.get("narration")); 

But I immediately get this error:

Invocation of form get(string) doesn't match definition get(optional string or array or object keys, function callback)

I have been searching for many hours trying to find a solution but I can't make it work. I thing that I just need to check if the value is already defined so if It isn't, I could use set() method to store my default value.

2 Answers 2

10

The function expects a callback:

chrome.storage.local.get("narration", function(data) { if(chrome.runtime.lastError) { /* error */ return; } var bookNarration = parseInt(data.narration); switch(bookNarration) { /* ... */ }; }); 
Sign up to request clarification or add additional context in comments.

1 Comment

In my Chrome app, this chrome.runtime.lastError never work. i'm suprise that they didn't find a smartest way to manage error. It's easier with LocalStorage var students = JSON.parse(localStorage.getItem('studentsInfo') || [];
1

There's no need to use the catch now (meaning I don't know if this changed since the accepted answer and now).

You can pass in the item(s) you want along with defaults should the item not exist

chrome.storage.local.get({narration: "", num: 0, books: []}, function(data) { var bookNarration = parseInt(data.narration); switch(bookNarration) { var numBooks= data.books.length /* ... */ }; }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.