Léo Martin
Léo Martin

Reputation: 3

Chrome.storage.local get wrong value

I'm trying to load content from chrome.storage.local but it doesn't work (it always return the same result, [object OBJECT]). This is my code :

    function load()
{
    var loginC = "";
    chrome.storage.local.get('loginC', function(result){
    loginC = result;
        if (loginC != "") {
            document.getElementById("login").value = loginC;
        }
    });

    var passC = "";
    chrome.storage.local.get('passC', function(result){
    passC = result;
        if (passC != "") {
            document.getElementById("pass").value = passC;
        }
    });
}

load();

Upvotes: 0

Views: 480

Answers (2)

user235273
user235273

Reputation:

The get method returns an object in the format {loginC: /*..*/ } for the result variable. Use result.loginC and result.passC to get the value.

Upvotes: 1

Xan
Xan

Reputation: 77571

As the documentation states, the callback receives an object containing the results:

The callback parameter should be a function that looks like this:

function(object items) {...};

object items

Object with items in their key-value mappings.

It is done in this way, because one get operation can retrieve more than one value.

So in general, the code should look like this:

chrome.storage.local.get('keyName', function(result) {
  /* use result.keyName */
});

And your code can be simplified to this:

chrome.storage.local.get(['loginC', 'passC'], function(result) {
    if (result.loginC) { // Will catch both "" and undefined
        document.getElementById("login").value = result.loginC;
    }
    if (result.passC) {
        document.getElementById("pass").value = result.passC;
    }
});

Upvotes: 1

Related Questions