我正试图根据chrome.storage.local中存储的数据,在我的谷歌chrome扩展中阻止某些Web请求。然而,由于chrome的异步方式,我找不到在onBeforeRequest.addListener的回调函数内部返回"{cancel:true};"的方法,也找不到从storage.local访问其各自回调函数之外的数据的方法。Storage.local.get().
这是我的相关代码。
chrome.webRequest.onBeforeRequest.addListener( function(info) {
chrome.storage.local.get({requests: []}, function (result) {
// depending on the value of result.requests.[0].item I want to return "{cancel: true };" in order to block the webrequest
if(result.requests.[0].item == 0) return {cancel: true}; // however this is obviously in the wrong place
});
// if I put return {cancel: true} here, where it should be, I can't access the data of storage.local.get anymore
// if(result.requests.[0].item == 0) return {cancel: true};
});
有人能解决这个问题吗?谢谢你的帮助。
您只需交换回调:
chrome.storage.local.get({requests: []}, function (cache) {
chrome.webRequest.onBeforeRequest.addListener(function (request) {
if(cache.requests[0].item === 0)
return { cancel: true };
});
});
这是有道理的,因为您不是在每次请求时请求存储,而是只在内存中有存储后才侦听请求。
这种方法唯一的缺点是,如果在开始侦听后更新存储,它将不会生效。
要解决此问题,请删除侦听器并重新添加它:
var currentCallback;
function startListening() {
chrome.storage.local.get({requests: []}, function (cache) {
chrome.webRequest.onBeforeRequest.addListener(function (request) {
currentCallback = this;
if(cache.requests[0].item === 0)
return { cancel: true };
});
});
}
function update() {
if (typeof currentCallback === "function") {
chrome.webRequest.onBeforeRequest.removeListener(currentCallback);
currentCallback = null;
}
startListening();
}