Javascript 从 chrome.storage.sync 保存和检索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14531102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:07:36  来源:igfitidea点击:

saving and retrieving from chrome.storage.sync

javascriptgoogle-chromegoogle-chrome-extension

提问by source.rar

I am trying to save a data object in chrome sync storage and then retrieve it, however the get() function always returns an empty object. The code I am using is,

我试图在 chrome 同步存储中保存一个数据对象,然后检索它,但是 get() 函数总是返回一个空对象。我使用的代码是,

function storeUserPrefs() {
    var key='myKey', testPrefs = {'val': 10};
        chrome.storage.sync.set({key: testPrefs}, function() {console.log('Saved', key, testPrefs);});
}

function getUserPrefs() {
    chrome.storage.sync.get('myKey', function (obj) {
        console.log('myKey', obj);
    });
}

Could someone please tell me what I am doing wrong here?

有人可以告诉我我在这里做错了什么吗?

回答by Sudarshan

The problem is with chrome.storage.sync.set({key: testPrefs}

问题在于 chrome.storage.sync.set({key: testPrefs}

Your data is stored as

您的数据存储为

{
    key: "{"val":10}"
}

So, your code chrome.storage.sync.get('myKey')return undefined\empty object.

因此,您的代码chrome.storage.sync.get('myKey')返回undefined\empty object

Solution I

解决方案一

Use string "key"as your key

使用字符串"key"作为您的键

chrome.storage.sync.get("key", function (obj) {
    console.log(obj);
});

or

或者

Solution II

方案二

Set data through "myKey"Key.

通过"myKey"Key设置数据。

chrome.storage.sync.set({"myKey": testPrefs}

P.S: Don't forget chrome.storage.syncis permanent storage API, Use chrome.storage.sync.clearbefore any further testing to see changes

PS:不要忘记chrome.storage.sync是永久存储 API,在进一步测试之前使用chrome.storage.sync.clear以查看更改

References

参考

EDIT 1

编辑 1

Use this code to set variable value in Chrome.storage

使用此代码在 Chrome.storage 中设置变量值

function storeUserPrefs() {
    var key = "myKey",
        testPrefs = JSON.stringify({
            'val': 10
        });
    var jsonfile = {};
    jsonfile[key] = testPrefs;
    chrome.storage.sync.set(jsonfile, function () {
        console.log('Saved', key, testPrefs);
    });

}

It generates following Output

它生成以下输出

Object{
    myKey: "{"val":10}"
}

回答by danieluy

function storeUserPrefs() {
    var key='myKey', testPrefs = {'val': 10};
    chrome.storage.sync.set({[key]: testPrefs}, function() {
      console.log('Saved', key, testPrefs);
    });
}

You could just force to evaluate the variable key using [key] when saving. That way is easy to set your keys dynamically. Hope that helps.

您可以在保存时使用 [key] 强制评估变量键。这种方式很容易动态设置您的密钥。希望有帮助。

回答by bde-maze

A more fancy way to do it, and it handles errors as well:

一种更奇特的方法,它也能处理错误:

const getStorageData = key =>
  new Promise((resolve, reject) =>
    chrome.storage.sync.get(key, result =>
      chrome.runtime.lastError
        ? reject(Error(chrome.runtime.lastError.message))
        : resolve(result)
    )
  )

const { data } = await getStorageData('data')


const setStorageData = data =>
  new Promise((resolve, reject) =>
    chrome.storage.sync.set(data, () =>
      chrome.runtime.lastError
        ? reject(Error(chrome.runtime.lastError.message))
        : resolve()
    )
  )

await setStorageData({ data: [someData] })

回答by Eneas Gesing

As chrome.storage.sync can storage JS objects, you can just do this:

由于 chrome.storage.sync 可以存储 JS 对象,您可以这样做:

var save = {};
save["myKey"] = testPrefs;

chrome.storage.sync.set(save, function() {
    console.log('Settings saved');
});

回答by user3018868

testPrefs = JSON.stringify({
            'val': 10
        });
    var jsonfile = {};
    jsonfile[key] = testPrefs;
    chrome.storage.sync.set(jsonfile, function () {
        console.log('Saved', key, testPrefs)