Google Chrome扩展跨域XMLHttpRequest

Google Chrome extension Cross Domain XMLHttpRequest

本文关键字:XMLHttpRequest 扩展 Chrome Google      更新时间:2023-09-26

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

我已将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"]
}

我在其中调用API的Javascript函数是:

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

哦,我以前从未回答过任何问题,如果我的格式很糟糕,我很抱歉。

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

api文档规定所有内容都必须小写,所以我将其添加到了translate()函数中。还添加了responseType=json。任何格式错误的参数都会导致404错误,从而导致"Access Control Allow Origin"错误,因此需要注意这一点。

以下是我在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');

这一切对我来说都很有效,所以我希望它会对你有用:)