0

我有一个扩展,它需要来自本地存储的一些数据。算法:如果数据未找到(或为空)则 alert(); 并返回;

var storage = chrome.storage.local;
storage.get('data', function(items) 
{ 
    if (!items.data.apiKey) { alert('Api key not set!'); return;} // not working
    //nextstuff that is not working if there is no items.data.apiKey
}

此代码在 Windows 上运行良好。在 Mac OS 中它不会提醒我,如果它不返回数据,它会返回。

4

1 回答 1

0

我怀疑您的代码不会因为 OS X 而失败。

真正的问题是您正在读取items.data. 通过这样做,您假设它items.data是一个非空值(不是nullundefined)。这个假设是错误的。

为了解决这个问题,添加一个额外的检查:

chrome.storage.local.get('data', function(items) { 
    if (!items.data || !items.data.apiKey) {
        alert('Api key not set!');
        return;
    }
});

如果你愿意,你也可以设置一个默认值,如下:

chrome.storage.local.get({data: 'default value'}, function(items) { 
    /* ... */
});
于 2013-08-28T08:36:57.863 回答