Chrome扩展:Chrome本地存储不立即设置



我在Chrome本地存储设置和检索方面遇到了奇怪的问题。

background.js中,当页面加载完成后获取某个URL的HTML时,我正在设置它,然后在content.js中,我正在从本地存储中获取值。有时它是即时存储和提取的,而其他时候results.htmlundefined。如果我使用chrome.storage.local.clear(),它会让它更糟糕,让你刷新页面至少2-3次。下面是我的代码:

background.js

chrome.runtime.onMessage.addListener(
async function(request, sender, sendResponse) {
// Reset storage
// chrome.storage.local.clear() // it is lagging refreshing values
sendResponse("bar")
// Check whether it is correct URL
var url = 'http://localhost:8000/get.php?url='+request
console.log('URL for AJAX =',url)
var result = await sendReq(url)
var json_result  = JSON.parse(result)
var status = json_result['status'] 
var rules = []
console.log('Status = '+status)
if(status == 'ok') {
rules = json_result['msg']['rules']
chrome.storage.local.set({'rules': rules}, function() {}); 

url = 'http://localhost:8000/read.php?url='+request
result = await sendReq(url)
// console.log(result)
chrome.storage.local.set({'html': result}, function() {}); // this goes undefined if the URL of visiting page is changed.
} else {
// To check on content script
chrome.storage.local.set({'html': '__FAIL__'}, function() {}); 
}
}
);

content.js(使用JQuery)

$(function() {
// console.clear()
console.log('The Agile Super Cluster extension cleared all previous output')
chrome.storage.local.get(['html','rules'], function(result) {
// Do not perform things below if it is not a relevant Super Cluster URL
if(result.html == '__FAIL__' || typeof (result.html) == 'undefined') {
return
}
.....
// Out of onReady() block
chrome.runtime.sendMessage(
url,
function (response) {
console.log('Sending Response')
console.log(response);
}
);

解决方案是正确使用消息传递,这样您就可以可靠地等待结果。

  1. 去除铬。
  2. 从onMessage监听器中删除async(为什么?)并使用单独的异步函数获取信息;
  3. 通过sendResponse+return true返回结果。

content.js:

chrome.runtime.sendMessage(url, res => {
console.log(res);
if (res.html) {
// use `res.html` here
}
});

background.js:

const API_GET = 'http://localhost:8000/get.php?url=';
const API_READ = 'http://localhost:8000/read.php?url=';
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
getInfo(request).then(sendResponse);
return true; // keep the channel open for asynchronous sendResponse
});
async function getInfo(url) {
const res = JSON.parse(await sendReq(`${API_GET}${url}`));
return res.status === 'ok' ? {
rules: res.msg.rules,
html: await sendReq(`${API_READ}${url}`),
} : {};
}

最新更新