【问题标题】:How to get chrome storage values via local getter setter class?如何通过本地 getter setter 类获取 chrome 存储值?
【发布时间】:2017-11-06 05:51:33
【问题描述】:

我在 JavaScript 文件中创建了一个本地类,其内容如下:

class CustomChromeStorage {
    //#region userName
    get userName() {

        let isCurrentValueSet = false;
        chrome.storage.sync.get('userName', function (obj) {
            this._userName = obj;
            isCurrentValueSet = true;
        });
        while (true) {
            if (isCurrentValueSet) {
                return this._userName;
            }
        }
    }

    set userName(newValue) {
        this._userName = newValue;
        chrome.storage.sync.set({ 'userName': newValue }, function () {
        });
    }
    remove_userName() {
        this._userName = null;
        chrome.storage.sync.remove('userName', function () {
        });
    }
    //#endregion userName

我做这种类型代码的想法是当我在我的代码中的其他地方写这样的:

alert(new CustomChromeStorage().userName);

然后我的代码只是从 chrome 存储中获取用户名并通过警报显示它。为了从 chrome 存储中获取一个值,我们需要提供一个回调作为参数值。我知道这是异步过程的好习惯,但有时处理所有回调对我来说变得很麻烦。

我希望当我通过自定义类从 chrome 存储中获取值时异步执行当前代码。这就是为什么我在该属性的 getter 方法中编写了无限 while 循环,但问题是当我尝试通过自定义 chrome 存储类提醒用户名时,我的整个程序执行会挂起。

它背后的原因是我最初设置了isCurrentValueSet = false,它在while循环中永远不会为真。

如果有人知道为什么它在 while 循环中没有设置为 true,请告诉我。

【问题讨论】:

    标签: javascript google-chrome-extension asynccallback google-chrome-storage


    【解决方案1】:

    sync.get 返回的 obj 是 {userName: value} - 使用 obj.userName。

    isCurrentValueSet 未设置为 true 的原因是该函数是异步的 - 当回调执行时,它无权访问类变量 isCurrentValueSet。

    你想要达到的目的是错误的。事实上,为了用户和浏览器的性能,存储请求是异步的。你必须学会​​围绕它进行设计,当你习惯了它就很容易了。

    您可以一次检索多个变量,因此如果您有一段代码需要多个变量,只需执行以下操作:

    chrome.storage.sync.get({a:"",b:"",c:0,d:[]}, function(result) {
      a = result.a
      b = result.b
      c = result.c
      d = result.d
      your code
    });
    

    通过传入一个对象,您可以请求多个变量并定义默认值(如果它们尚不存在于存储中)。当然你没有有来提取变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-10
      • 2015-04-08
      相关资源
      最近更新 更多