如何通过本地gettersetterclass获取chrome存储值?
How to get chrome storage values via local getter setter class?
我在 JavaScript 文件中创建了一个包含以下内容的本地 class:
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 存储中获取值,我们需要提供一个回调,并将该值作为参数。我知道这是异步过程的好习惯,但有时处理所有回调对我来说变得很麻烦。
我希望当我通过自定义 class 从 chrome 存储中获取值时异步执行当前代码。这就是为什么我在那个 属性 的 getter 方法中编写了无限 while 循环,但问题是当我尝试通过自定义 chrome 存储 class 来提醒用户名时,我的整个程序执行挂起。
其背后的原因是我最初设置了 isCurrentValueSet = false
,它在 while 循环中永远不会变为真。
如果有人知道为什么它在 while 循环中没有设置为真,请告诉我。
从 sync.get 返回的对象是 {userName: value} - 使用 obj.userName.
isCurrentValueSet 未设置为 true 的原因是该函数是异步的 - 当回调执行时,它无法访问 class 变量 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
});
通过传入对象,您可以请求多个变量并且定义默认值(如果它们不存在于存储中)。当然,您 没有 来提取变量。
我在 JavaScript 文件中创建了一个包含以下内容的本地 class:
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 存储中获取值,我们需要提供一个回调,并将该值作为参数。我知道这是异步过程的好习惯,但有时处理所有回调对我来说变得很麻烦。
我希望当我通过自定义 class 从 chrome 存储中获取值时异步执行当前代码。这就是为什么我在那个 属性 的 getter 方法中编写了无限 while 循环,但问题是当我尝试通过自定义 chrome 存储 class 来提醒用户名时,我的整个程序执行挂起。
其背后的原因是我最初设置了 isCurrentValueSet = false
,它在 while 循环中永远不会变为真。
如果有人知道为什么它在 while 循环中没有设置为真,请告诉我。
从 sync.get 返回的对象是 {userName: value} - 使用 obj.userName.
isCurrentValueSet 未设置为 true 的原因是该函数是异步的 - 当回调执行时,它无法访问 class 变量 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
});
通过传入对象,您可以请求多个变量并且定义默认值(如果它们不存在于存储中)。当然,您 没有 来提取变量。