Javascript 基于chrome.storage中的数据返回chrome.webRequest.onBeforeRequest的值
我正试图根据存储在chrome.storage.local中的数据阻止我的google chrome扩展中的某些Web请求。 但是,我找不到在onBeforeRequest.addListener的回调函数中返回“{cancel:true};”的方法。或者,由于chrome.storage.local.get()的异步方式,在其各自的回调函数之外从storage.local访问数据 这是我的相关代码Javascript 基于chrome.storage中的数据返回chrome.webRequest.onBeforeRequest的值,javascript,google-chrome-extension,storage,webrequest,Javascript,Google Chrome Extension,Storage,Webrequest,我正试图根据存储在chrome.storage.local中的数据阻止我的google chrome扩展中的某些Web请求。 但是,我找不到在onBeforeRequest.addListener的回调函数中返回“{cancel:true};”的方法。或者,由于chrome.storage.local.get()的异步方式,在其各自的回调函数之外从storage.local访问数据 这是我的相关代码 chrome.webRequest.onBeforeRequest.addListener( f
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();
}
太好了,问题解决了。但现在我遇到了一个问题,在我更改了本地存储中的一些数据,然后重新加载页面之后,onBeforeRequest.addListener会被触发两次。