在过去的两天里,我一直在使用chrome异步存储.如果你有一个功能,它的工作"很好".(如下):
chrome.storage.sync.get({"disableautoplay": true}, function(e){
console.log(e.disableautoplay);
});
Run Code Online (Sandbox Code Playgroud)
我的问题是我无法使用我正在做的功能.我想把它归还,就像LocalStorage一样.就像是:
var a = chrome.storage.sync.get({"disableautoplay": true});
Run Code Online (Sandbox Code Playgroud)
要么
var a = chrome.storage.sync.get({"disableautoplay": true}, function(e){
return e.disableautoplay;
});
Run Code Online (Sandbox Code Playgroud)
我已经尝试了一百万种组合,甚至设置一个公共变量并设置:
var a;
window.onload = function(){
chrome.storage.sync.get({"disableautoplay": true}, function(e){
a = e.disableautoplay;
});
}
Run Code Online (Sandbox Code Playgroud)
什么都行不通.它都返回undefined,除非引用它的代码在get函数内部,这对我来说没用.我只是希望能够将值作为变量返回.
这甚至可能吗?
编辑:这个问题不重复,请允许我解释原因:
1:没有其他帖子专门询问这个问题(我花了两天时间先查看,以防万一).
2:我的问题仍未得到解答.是的,Chrome Storage是异步的,是的,它不会返回值.那就是问题所在.我将在下面详细说明......
我需要能够在chrome.storage.sync.get函数之外获取存储值.我无法使用localStorage,因为它是特定于URL的,并且无法从chrome扩展的browser_action页面和background.js访问相同的值.我无法使用一个脚本存储值并使用另一个脚本访问它.他们分开对待.
所以我唯一的解决方案是使用Chrome存储.必须有某种方法来获取存储项的值并在get函数之外引用它.我需要在if语句中检查它.
就像localStorage可以做的那样
if(localStorage.getItem("disableautoplay") == true);
Run Code Online (Sandbox Code Playgroud)
必须有一些方法可以做一些事情
if(chrome.storage.sync.get("disableautoplay") == true);
Run Code Online (Sandbox Code Playgroud)
我意识到这不会那么简单,但这是我解释它的最佳方式.
我看到的每个帖子都说这样做:
chrome.storage.sync.get({"disableautoplay": true, function(i){
console.log(i.disableautoplay);
//But the info is worthless to me inside this function.
});
//I need it outside this function.
Run Code Online (Sandbox Code Playgroud) javascript function return-value google-chrome-extension google-chrome-storage