构建chrome扩展时可能遇到的一个常见问题是,每次从chrome存储中检索数据时,都会返回UNDEFINED。让我举个例子。
var toStore = "This text shall be stored"
//Script saves toStore and callback function provides confirmation
chrome.storage.sync.set({"value": toStore}, function(){console.log("Value Saved!")});
然后通过获取值的事件激活函数:
var storedItem = chrome.storage.sync.get('value', function(){
console.log("Value Got! Value is " + value)});
或类似的东西,但它在控制台中的结果始终是:
Value Got! Value is Undefined
我会告诉你如何避免这种情况。这也适用于chrome.storage.local.set。
答案 0 :(得分:1)
使用chrome.store.sync.get获取存储值时,实际函数不会返回保存的值。相反,它返回var“data”,其中包含存储值的名称 - 值对:
chrome.storage.sync.get('value', function(data){
console.log("Value Got! Value is " + data.value)});
然后将该值存储在名为“data。[VALUE-NAME]”的函数中。如果你运行它,你应该得到
Value Got! Value is This text shall be stored