You can just swap the callbacks:
chrome.storage.local.get({requests: []}, function (cache) {
chrome.webRequest.onBeforeRequest.addListener(function (request) {
if(cache.requests[0].item === 0)
return { cancel: true };
});
});
This makes sense because instead of requesting storage on each request, you only listen to requests after you have the storage in the memory.
The only downside to this method is that if you are updating the storage after starting listening, it won't take effect.
To solve this, remove the listener and add it again:
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();
}