Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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
        /* ... */
    };
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top