javascript - 根据 chrome.storage 中的数据返回 chrome.webRequest.onBeforeRequest 的值

标签 javascript google-chrome-extension storage webrequest

我试图根据存储在 chrome.storage.local 中的数据阻止我的 google chrome 扩展程序中的某些网络请求。 但是我找不到返回“{cancel: true };”的方法onBeforeRequest.addListener 的回调函数里面。或者由于 chrome.Storage.local.get() 的异步方式,在其各自的回调函数之外从 storage.local 访问数据。

这是我的相关代码。

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

关于javascript - 根据 chrome.storage 中的数据返回 chrome.webRequest.onBeforeRequest 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18577755/

相关文章:

javascript - Mapbox JavaScript : Clicking on a Marker and highlighting a corresponding list

javascript - 抛出新的类型错误 ('app.use() requires middleware functions' );

javascript - 如何在不与 svelte 中的编译器对抗的情况下避免循环依赖?

javascript - Light DOM 样式泄漏到 Shadow DOM 中

azure - 如何在 Azure Synapse 中使用 PySpark 将文件装载为文件对象

security - 将 Cookie 存储在数据库中安全吗?

android - Commit 上的数据未保存在共享首选项中

javascript - 加载 AJAX 的 div 中的 HTML 表单 radio 值

javascript - 删除 chrome 扩展中的 chrome.alarms 监听器

javascript - Chrome 扩展 : load and execute external script