1

由於某些原因,當我嘗試使用我的Chrome擴展程序時,我總是收到以下錯誤; 拒絕加載腳本'http://dynamic.xkcd.com/api-0/jsonp/comic/1123?callback=random&_=1411616016083',因爲它違反了以下內容安全策略指令:「script-src」self'chrome-extension-resource:「。無法對我的Chrome擴展程序執行HTTP請求

這裏是我的代碼:

的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 
      }) 
     ); 
    } 
}); 

回答

3

你不應該使用JSONP一個延伸,因爲它涉及前依靠服務器提供的代碼,這就是錯誤所在。您可以直接訪問json:

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

記得更新清單中的權限以允許該主機。並從您的參數中刪除jsonpCallback字段。

相關問題