我试图根据存储在 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/