在Chrome扩展程序中阻止了CORS请求

时间:2019-08-25 16:26:41

标签: ajax google-chrome google-chrome-extension

我是chrome扩展程序开发的新手。我试图从简单的API服务中获取JSON文件,但没有成功,$.getJSON方法将被阻止,因为它是CORS请求,并且不允许使用。我已经在SO上阅读了一些问题,但是我无法弄清楚如何继续向API服务发出Ajax请求,任何人都可以向mw举例说明吗?我只有popup.html文件和popup.js文件,其中包含我的逻辑和布局,扩展文件夹中没有background.js文件,这是必需的吗?

这是我得到的错误:

Access to XMLHttpRequest at '...' (redirected from '...') from origin 'chrome-extension://mhgnneiaahgopaabnljbmglekgbaanio' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

注意:我已经将权限添加到api网址

清单


{
  "name": "ChMStats",
  "short_name": "CBMS",
  "version": "1.0",
  "author": "P",
  "description": "!",
  "manifest_version": 2,
  "permissions": [
    "tabs",
    "https://siteurl.com/api/*"
  ],
  "browser_action": {
    "default_popup": "popup.html"
  }
}

popup.js

(function($){
  $(document).ready(function(){
    console.log('Extension Started!');
    const url = 'https://siteurl.com/api/?user=username&token=token';
    $('#getStats').on('click', function(e){
      e.preventDefault();
      $('.spinner-grow').css({'display':'block'});
      $.getJSON(url, function(response){
        $('.spinner-grow').css({'display':'none'});
          var html = '<li class="list-group-item list-group-item-action">Username '+response.username+'</li>';
          html += '<li class="list-group-item d-flex justify-content-between align-items-center">Token Balance <span="badge badge-danger badge-pill">'+response.token_balance+'</span></li>';
          $('.response').append(html);
      });
    });
  });
}(jQuery));


0 个答案:

没有答案