我正在尝试编写一个 Chrome 扩展,它会在加载时关闭选项卡并包含特定关键字,我将其存储在 banned.json
中。但以下代码给了我一个错误:
//background.js:
var obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
obj = JSON.parse(xhttp.response);
console.log(obj.banned);
}};
xhttp.open('GET', "banned.json", true);
xhttp.send();
chrome.webNavigation.onCompleted.addListener(closeTab, obj.banned); // error is here
function closeTab(e) {
if (!e.frameId) {
console.log("Hallo2");
chrome.tabs.remove(e.tabId);
}
}
它说它无法读取未定义的禁止属性。怎么可能? obj
在第一行中定义,我可以在 if-block
中引用它。谁能帮我吗?
编辑:
banned.json
:
{
"banned": [
"https://www.google.de/",
"youtube.com"
]
}
最佳答案
您需要将“chrome.webNavigation.onCompleted.addListener”语句放入“xhttp.onreadystatechange”函数中。
var obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
obj = JSON.parse(xhttp.response);
console.log(obj.banned);
chrome.webNavigation.onCompleted.addListener(closeTab, obj.banned);
}};
xhttp.open('GET', "banned.json", true);
xhttp.send();
function closeTab(e) {
if (!e.frameId) {
console.log("Hallo2");
chrome.tabs.remove(e.tabId);
}
}
编辑
您可以尝试按如下方式更改banned.json。
{
"banned":
"url" : [
{"hostContains":"https://www.google.de/"},
{"hostContains":"youtube.com"}
]
}
关于javascript - 我无法在函数调用中使用之前通过 AJAX 请求加载的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59251858/