Chrome.storage.sync.set/get isn't working

Chrome.storage.sync.set/get isn't working

本文关键字:working isn get storage sync set Chrome      更新时间:2023-09-26

构建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.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