![](/img/trans.png)
[英]chrome.webRequest.onBeforeRequest.addListener Cannot read property 'onBeforeRequest' of undefined
[英]chrome.webRequest.onBeforeRequest.addListener not blocking an array of urls
我正在尝试根据用户输入阻止一组网址。 我具有JSON格式的url数组,但是当我导航到这些站点时,这些站点实际上并未被阻止。 如果我只使用一个站点而不是一个阵列,则它确实会被成功阻止。 这是功能。
function addListener(){
chrome.webRequest.onBeforeRequest.addListener(
function(){ return {cancel: true}; },
{
urls: blockedUrls()
},
["blocking"]
);
}
这是我的功能blockedUrls。
var blockedUrls = function () {
chrome.storage.sync.get(['block'], function(result) {
if (typeof result.block === 'undefined') {
//blocks is not yet set
var jobj = ["*://www.whatever.com/*"];
return [jobj[0]];
console.log("not set");
}
else{
var xt = JSON.parse(result.block);
console.log(JSON.stringify(xt.urls));
return JSON.stringify(xt.urls);
}
});
return ["*://www.whatever.com/*"];
}
console.log确实打印出了我想要的东西,这就是(显然有些只是用于测试)
["doesntexist.com","*://www.yahoo.com/*","*://www.xbox.com/*","*://www.hello.com/*","*://www.es/*"]
而且,如果有帮助,这里是从变量request.newSites初始将站点设置为chrome存储的地方。
var jsonStr = '{"urls":["doesntexist.com"]}';
var obj = JSON.parse(jsonStr);
//add url matching patterns to the urls from user input
for (var i = 0; i < request.newSite.length; i++){
obj['urls'].push( '*://www.' + request.newSite[i] + '/*');
}
jsonStr = JSON.stringify(obj);
chrome.storage.sync.set({'block': jsonStr}, function(){
addListener();
});
提前致谢。
chrome.storage.sync.get
是一个异步函数。 因此,它不会返回您的网址列表。
您可能打算做的是以下操作:
function addListener(){
chrome.storage.sync.get(['block'], function(result) {
let urls;
if (typeof result.block === 'undefined') {
//blocks is not yet set
var jobj = ["*://www.whatever.com/*"];
urls = [jobj[0]];
console.log("not set");
}
else{
var xt = JSON.parse(result.block);
console.log(JSON.stringify(xt.urls));
urls = JSON.stringify(xt.urls);
}
chrome.webRequest.onBeforeRequest.addListener(
function(){ return {cancel: true}; },
{
urls: urls
},
["blocking"]
);
});
}
您的代码有两个问题:
1) chrome.storage.sync.get
的回调函数是异步的 。 因此,在函数blockedUrls
,返回值将始终为["*://www.whatever.com/*"]
,因为该行return ["*://www.whatever.com/*"];
将在chrome.storage.sync.get
的回调函数之前运行。
2) chrome.webRequest.onBeforeRequest
侦听器的第二个参数应为以下形式的对象: {urls: theUrls}
其中theUrls
是字符串数组 ,而不是字符串。
除此之外,您可以利用chrome.storage
可以直接存储对象和数组的事实,因此无需对其进行字符串化。
尝试:
var obj = {urls: ['*://doesntexist.com/*']};
for (var i = 0, j = request.newSite.length; i < j; i++){
obj.urls.push( '*://www.' + request.newSite[i] + '/*');
}
chrome.storage.sync.set({block: obj}, function(){
addListener();
});
function addListener() {
chrome.storage.sync.get('block', function (result) {
var myUrls = result.block || ["*://www.whatever.com/*"];
chrome.webRequest.onBeforeRequest.addListener(function(){
return {cancel: true}
},
{urls: myUrls},
["blocking"] );
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.