Chrome扩展程序:无法为外部json加载资源

时间:2013-01-30 17:53:20

标签: javascript json api google-chrome-extension

我一直在搜索stackoverflow和谷歌寻找答案,但我找不到任何东西......我还是刚接触javascript,所以我有点困惑;

的manifest.json

{
  "manifest_version": 2,

  "name": "Twitch Streams List",
  "description": "Find all the streams directly through Chrome",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
   "permissions": [
    "http://api.twitch.tv/kraken/streams?limit=20"
  ],
  "web_accessible_resources": ["twitch.js"]
}

popup.html

<!doctype html>
<html>
  <head>
    <title>Getting top streams from Twitch</title>
    <style>
      body {
        min-width: 350px;
      }
    </style>
    <script src="twitch.js" type="text/javascript"></script>
  </head>
  <body>
  </body>
</html>

twitch.js

var streamGenerator = {
  /* url where to get the streams from */
  url: chrome.extension.getURL('http://api.twitch.tv/kraken/streams?limit=20'),

  /* go get the streams from the json at the url given */
  requestStreams: function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', this.url, true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        var resp = JSON.parse(xhr.responseText);
      }
    }
    xhr.send();
  },

  /* import the streams in the html page */
  showStreams: function (e) {
    var streams = resp.streams;
    var output = '<ul>';

    for (var i = 0; i < streams.length; i++) {
      output += '<li>' + streams[i].channel.display_name + ' - ' + streams[i].channel.viewers + ' - ' + streams[i].channel.game + '</li>';
    }

    output += '</ul>';
    console.log(output);
    document.body.appendChild(output);
  }
};

/* Run the script as soon as the popup is loaded */
document.addEventListener('DOMContentLoaded', function () {
  streamGenerator.requestStreams();
});

弹出窗口中没有任何内容,控制台显示

Failed to load resource chrome-extension://dihpppnflhlpkehcgnjggjcipffmjlgp/http://api.twitch.tv/kraken/streams?limit=20

怎么做???

由于

2 个答案:

答案 0 :(得分:2)

'api.twitch.tv/kraken/streams?limit=20'不在您的安装目录中,因此请勿将其作为参数传递给chrome.extension.getURL

话虽如此,XHR无法获取跨域内容。您可能想看看他们是否提供了像JSONP这样的替代方案。

答案 1 :(得分:1)

值得注意的是:

http://api.twitch.tv/kraken/streams?limit=20返回404

https://api.twitch.tv/kraken/streams?limit=20返回JSON

(twitch api需要SSL)