0

I'm making a chrome extension which saves a list of URLs using the chrome.storage API. I'm storing this list in an array with the key "tabs". Basically, the refreshList() function calls when the 'browser action' is called. This calls the getList() function to get the array of URLs. The console.log() calls from getList() show that it is working fine (they print out the array object and "is array"), but in refreshList() the console.log prints our "undefined" and an error occurs saying Uncaught TypeError: Cannot read property 'length' of undefined.

function refreshList()
{
    var items = getList();
    console.log(items);
    var list = document.getElementById('pin-list');
    for (var i = 0; i < items.length; i++)
    {
        var entry = document.createElement("li");
        entry.appendChild(document.createTextNode(items[i]));
        list.appendChild(entry);
    }
}

function getList()
{
    var itemsOut;
    chrome.storage.local.get("tabs",function (items){
        itemsOut=items.tabs;
        console.log(itemsOut);
        if (itemsOut instanceof Array)
        {
            console.log("is array");
            return itemsOut;
        }
        else if (typeof(itemsOut)=="undefined")
        {
            console.log("is undefined");
            return [];
        }
        console.log("is something else");
        chrome.storage.local.set({"tabs":[itemsOut]},function(){});
        return [itemsOut];
    });    
}

The refreshList() function should print out an unordered list of the items in chrome.storage onto the browser action popup.

I'm thoroughly confused. I think it has something to do with passing by reference (or, if I understand it correctly, passing by value where the value is a reference) but I'm not sure how to fix it. I hope this was clear enough to understand... Thank you in advance :)

dram
  • 97
  • 1
  • 8
  • `getList()` returns nothing. – elclanrs Dec 10 '13 at 11:17
  • oh... nevermind... i feel rather stupid now... – dram Dec 10 '13 at 11:19
  • Also, you may want to take a look here http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs Dec 10 '13 at 11:22
  • I changed it so that `itemsOut` was set to whatever would have been returned, and returned itemsOut but the same thing still happened. Does that have something to do with the asynchronous stuff? – dram Dec 10 '13 at 11:29
  • Yes, if your code is async it would return before it has time to finish, thus `undefined`. Follow the link above, it has an in-depth analysis of the problem. – elclanrs Dec 10 '13 at 11:31

0 Answers0