chrome.storage.local.get() 获取存储处理并计数,内部计数正常,外部使用始终为0,百思不得其解。
如何在继续执行之前等待异步chrome.storage.local.get()完成-腾讯云开发者社区-腾讯云 (tencent.com)
原来我忽略了异步问题,最简单的方案就是一次取多个值,并在内部完成所有操作!
javascript
chrome.storage.local.get(['is_light', 'is_hide', 'keyword_light', 'keyword_hide'], function (result) {
//console.log(result);
if (result.is_light) {
var s = result.keyword_light;
var sl = s.split(';');
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < sl.length; j++) {
if (a[i].textContent.indexOf(sl[j]) != -1) {
a[i].style.color = 'white';
a[i].style.backgroundColor = '#DA3434';
a[i].innerHTML = a[i].textContent;
count_light++;
}
}
}
}
if (result.is_hide) {
var s = result.keyword_hide;
var sl = s.split(';');
var a = document.getElementsByTagName('a');
for (var i=0; i<a.length; i++) {
for (var j=0; j<sl.length; j++) {
if (a[i].innerHTML.indexOf(sl[j]) != -1) {
a[i].style.display = 'none';
count_hide++;
}
}
}
}
var s = count_light + '+' + count_hide;
chrome.runtime.sendMessage({ badgeText: s }, function(response) {
//console.log('return: ' + response.farewell);
});
});