How to check if a variable is set on chrome storage

Juan David Saab picture Juan David Saab · Feb 28, 2013 · Viewed 7.8k times · Source

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.

Answer

James McLaughlin picture James McLaughlin · Feb 28, 2013

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