How to check if a variable is set on chrome storage

I have a small snippet that works with LocalStorage, but I still can’t get it working on the Chrome Storage scheme.

When my application starts, I check the variable in localStorage

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

If this variable is undefined, it means that my application was opened for the first time, and after processing bookLanguage, I switched 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 as follows:

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

But I immediately get this error:

A call to the get (string) form does not match the definition of get (optional string or array or object keys, function callback)

I searched for many hours trying to find a solution, but I can't get it to work. I believe that I just need to check if a value is defined, so if it is not, I could use the set () method to store the default value.

+7
source share
2 answers

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) { /* ... */ }; }); 
+8
source

Now there is no need to use catch (this means that I do not know if this has changed since the adoption of the answer and now).

You can pass the elements you want along with the default values ​​if the element does not exist

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

All Articles