拒绝加载脚本Chrome扩展


Refused to load the script Chrome Extension

我正在尝试调用此站点并接收一个json对象。在给定CSP的chrome扩展中,我如何正确地与此API接口?

错误:拒绝加载脚本'http://thesaurus.altervista.org/service.php?word=smile&language=en_US&输出=json&key=REMOVEDMYKEY&callback=同义词库',因为它违反了以下内容安全策略指令:"script src'self'chrome扩展资源:"。

var word = "smile";
var s = document.createElement("script");
s.src = "http://thesaurus.altervista.org/service.php?word="+ word +"&language=en_US&output=json&key=REMOVEDMYKEY&callback=thesaurus";
document.getElementsByTagName("head")[0].appendChild(s);
function thesaurus(result) { 
  output = "";
  for (key in result.response) { 
list = result.response[key].list; 
output += list.synonyms+"<br>"; 
} 
if (output) 
document.getElementById("synonyms").innerHTML = output; 
}

您显示的URL明确表示它可以返回JSON对象。回调(JSONP样式)是可选的。

由于Chrome的扩展内容安全策略,您不能从该域使用JSONP。虽然您可以将白名单域添加到策略中,但出于安全原因,HTTP来源是被禁止的。

相反,您希望将JSON响应捕获为字符串并对其进行解析

您需要对该URL进行XHR调用:

function thesaurus(word) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    try {
      var result = JSON.parse(this.responseText);
      // Do something with the result
    } catch(e) {
      // Invalid JSON response
    }
  }
  xhr.onerror = function(e) {
    // Something bad happened
  }
  xhr.open(
    "GET",
    "http://thesaurus.altervista.org/service.php?word=" + word +
      "&language=en_US&output=json&key=REMOVEDMYKEY", 
    true
  );
  xhr.send();
}

您可能需要清单中的主机权限才能做到这一点,除非该服务器从任何来源启用了CORS(顺便说一句,这对这样的API来说都有意义)。

  "permissions": [
    "*://thesaurus.altervista.org/*"
  ],

请检查您的脚本是否声明了所需的权限,如下所述:https://developer.chrome.com/extensions/xhr#requesting-权限
https://developer.chrome.com/apps/app_external#external

在你的舱单里面应该有这样的东西:

"permissions": [
  "*http://thesaurus.altervista.org/*"
],