javascript - 我不能在函数调用中使用之前通过 AJAX 请求加载的对象
问题描述
我正在尝试编写一个 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"
]
}
解决方案
您需要在“xhttp.onreadystatechange”函数中放入“chrome.webNavigation.onCompleted.addListener”语句。
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"}
]
}
推荐阅读
- angularjs - 根据条件angularjs显示视图输入字段
- android - RadioButton 状态和按钮验证
- c# - Office365 - 使用 C# 列出用户
- python-3.x - 使用二维嵌套字典中的 if/else 语句进行列表理解循环
- node.js - nodejs到mosquitto raspberry pi pub sub不起作用
- java - PostgreSQL - 找不到适用于 JDBC 的驱动程序
- javascript - AJAX - JSON 未定义(jQuery、NodeJS)
- angular - 使用插值设置 routerLink
- symfony - Symfony 不验证实体
- python - pandas 0.23.1 AttributeError:“模块”对象没有属性“滚动”