【问题标题】:Can't do HTTP Request with my Chrome Extension无法使用我的 Chrome 扩展程序执行 HTTP 请求
【发布时间】:2014-09-25 03:35:08
【问题描述】:

由于某种原因,当我尝试使用我的 chrome 扩展程序时,我不断收到以下错误; 拒绝加载脚本“http://dynamic.xkcd.com/api-0/jsonp/comic/1123?callback=random&_=1411616016083”,因为它违反了以下内容安全策略指令:“script-src 'self' chrome-extension-resource:”。

这是我的代码:

Manifest.json

{
  "manifest_version": 2,

  "name": "XKCD New Tab",
  "description": "This extension demonstrates a browser action with kittens.",
  "version": "1.0",
  "permissions": [
    "tabs",
    "http://dynamic.xkcd.com/*"
  ],
   "chrome_url_overrides": {
    "newtab": "index.html"
  }

}

index.html

<html>
<head>
<title>New Tab</title>
<script src="jquery-2.1.1.min.js"></script>
<script src="testcode.js"></script>

</head>
<style>

h1 {
    font-family: Helvetica; 
    color:#3498db;
    font-weight: 100;
}
.container {
    text-align: center;
    background-color: #ecf0f1;
}



}

</style>
<body bgcolor="#ecf0f1">
<div id="xkcdcontent" class="container"></div>
</body>
</html>

testcode.js

 var x = Math.floor((Math.random() * 1420) + 1);


$.ajax({
    url: "http://dynamic.xkcd.com/api-0/jsonp/comic/"+ x +"?callback=?",
    dataType: "json",
    jsonpCallback: "random",
    success: function(data) {
        $("#xkcdcontent").append(
            $("<h1 style=text-align:center;/>").text(data.title),
            $("<img align=middle/>").attr({
                src: data.img,
                title: data.alt,
                alt: data.title
            })
        );
    }   
});

【问题讨论】:

    标签: javascript jquery json google-chrome google-chrome-extension


    【解决方案1】:

    您不应该使用扩展中的 jsonp,因为它涉及执行服务器提供的代码,而这就是错误所在。您可以使用以下方式直接访问 json:

    url: "http://xkcd.com/"+ x +"/info.0.json",
    

    请记住更新清单中的权限以允许此主机。并从您的参数中删除 jsonpCallback 字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 2023-03-20
      相关资源
      最近更新 更多