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

给你一囗甜甜゛ 提交于 2020-01-02 10:43:57

问题


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.


回答1:


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();
}


来源:https://stackoverflow.com/questions/18577755/return-value-of-chrome-webrequest-onbeforerequest-based-on-data-in-chrome-storag

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