0

我已经为Google Chrome创建了一个简单的扩展程序,但是我在访问字典API时遇到了问题。该API运行在我的扩展运行所在的不同域上。 我已阅读有关此主题的所有StackOverflow线程,但无法解决此问题。Google Chrome扩展程序跨域XMLHttpRequest

我已将API的地址添加到权限。它没有工作,所以我将其替换为http://*/*进行测试。我有以下manifest.json

{ 
"name": "web2memrise", 
"version": "0.3", 
"manifest_version": 2, 
"permissions": ["http://*/*"], 
"content_scripts": [{ 
    "matches": ["<all_urls>"], 
    "js": ["jquery.min.js", "contentscript.js"], 
    "css": ["style.css"] 
}], 
"web_accessible_resources": ["script.js", "jquery.min.js"] 
} 

JavaScript函数中,我使API调用:

function translateCallback(json){ 
    var translations = ""; 
    for(var phrase of json){ 
     translations += ", "+phrase.text; 
    } 
    translations = translations.substring(2).replace(", ", "\t") 
    popupContent(translations) 
} 

function translate(l1, l2, phrase){; 
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", "http://deu.hablaa.com/hs/translation/"+phrase+"/"+l1+"-"+l2+"/", true); 
    xhr.onreadystatechange = translateCallback 
    xhr.send(); 
} 

但它给我下面的错误:

home:19 GET http://nxtck.com/as.php?zid=48360&clbk=nextperf net::ERR_BLOCKED_BY_CLIENTloadScript @ home:19window.onload @ home:37 
(index):1 XMLHttpRequest cannot load http://deu.hablaa.com/hs/translation/solution/fra-eng/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.lefigaro.fr' is therefore not allowed access. 
script.js:44 Uncaught TypeError: json[Symbol.iterator] is not a function 

回答

0

哦,我”我从来没有回答过一个问题,如果我的格式是残暴的道歉。

首先,“xhr.onreadystatechange = translateCallback”是问题的根源,也许会导致错误的小雪球效应。所以我做了一个小小的改变来解决这个问题。我也改变了你的函数参数的顺序,以匹配它们在url中使用的顺序(使我更容易遵循)。

api文档声明一切都必须小写,所以我将它添加到了translate()函数中。还添加了responseType = json。任何格式不正确的参数都会导致404错误,从而导致“访问控制 - 允许 - 来源”错误,因此需要注意。

这是我在我的background.js中运行的内容,也在内容脚本中工作。

function translateCallback(json) { 
    var translations = ""; 
    for (var phrase of json) { 
     translations += ", " + phrase.text; 
    } 
    translations = translations.substring(2).replace(", ", "\t"); 

    /* console for testing only */ 
    console.log(translations); 

    /* uncomment this, commented out for testing */ 
    //popupContent(translations); 
} 

function translate(phrase, l1, l2) { 
    var url = "http://deu.hablaa.com/hs/translation/" + phrase + "/" + l1 + "-" + l2 + "/"; 

    /* api requires lowercase */ 
    url = url.toLowerCase(); 

    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", url, true); 

    /* added json for responseType */ 
    xhr.responseType = 'json'; 

    /* onload function added */ 
    xhr.onload = function() { 
     if (xhr.status === 200) { 
      translateCallback(xhr.response); 
     } 
    }; 

    /* error function added */ 
    xhr.onerror = function() { 
     /* error */ 
    }; 

    /* this was causing problems and need to be removed */ 
    //xhr.onreadystatechange = translateCallback 

    xhr.send(); 
} 
translate('blume', 'deu', 'eng'); 

这一切都为我工作,所以我希望它会为你:)