首页 > 解决方案 > 我不能在函数调用中使用之前通过 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"
    ]
}

标签: javascriptjsongoogle-chrome-extension

解决方案


您需要在“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"}
        ]
}

推荐阅读