return value of chrome.webRequest.onBeforeRequest based on data in chrome.storage

北慕城南 提交于 2019-12-06 09:46:51

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!