我想将某些数据存储在“本地存储到内容脚本”页面中。由于它不直接可用,因此我完成了它,chrome.runtime.sendMessage
但是我有几个值,看起来像这样。
var username, apikey, openexchange, currency, locale;
chrome.runtime.sendMessage({method: "getLocalStorage", key: "username"}, function(response) {
username = response.data;
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "apikey"}, function(response) {
apikey = response.data;
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "openexchange"}, function(response) {
openexchange = response.data;
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "currency"}, function(response) {
currency = response.data;
});
chrome.runtime.sendMessage({method: "getLocalStorage", key: "locale"}, function(response) {
locale = response.data;
});
当值增加时,此列表将更进一步,相反,是否还有其他方法可以将所有值包装在一个函数中?
任何帮助,将不胜感激。
我将首先回答您的直接问题(出于教育目的),然后提供一种更好的解决方法(根本不使用localStorage
)。
您是编写回答该getLocalStorage
方法的消息侦听器的人。因此,您可以通过为每个请求发送多个值来使其具有更多用途。
例子:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
switch(message.method) {
// ...
case "getLocalStorage":
if(message.key) { // Single key provided
sendResponse({data: localStorage[message.key]});
}
else if(message.keys) { // An array of keys requested
var data = {};
message.keys.forEach(function(key) {data[key] = localStorage[key];})
sendResponse({data: data});
}
break;
// ...
}
});
现在,您可以执行以下操作:
chrome.runtime.sendMessage(
{method: "getLocalStorage", keys: ["username", "apikey"]},
function(response) {
username = response.data.username;
apikey = response.data.apikey;
}
);
也就是说,您正在重新发明轮子。Chrome浏览器已经具备了存储API(称为,出奇,chrome.storage
),其地址正是这样的场景:某种持久存储可用于扩展页面和内容脚本两者。
添加"storage"
权限后,您可以执行以下操作:
chrome.storage.local.get(key, function(data) {
// Use data[key]
});
chrome.storage.local.get([key1, key2], function(data) {
// Use data[key1], data[key2]
});
chrome.storage.local.get({key1: default1, key2: default2}, function(data) {
// Use data[key1], data[key2], and defaults will be used if not yet in storage
});
chrome.storage.local.set({key1: value1, key2: value2});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句