I am trying to to block certain webrequests in my google chrome extension based on data stored in chrome.storage.local. However I can't find a way to return "{cancel: true };" inside the callback function of onBeforeRequest.addListener. Or to access data from storage.local outside of it's respective callback function due to the asynchronous way of chrome.Storage.local.get().
Here is my relevant code.
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};
});
Has anyone a solution for this problem? Thanks for your help.
You can just swap the callbacks:
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: