在chrome扩展中跨域ajax调用

时间:2016-03-01 17:07:22

标签: javascript jquery ajax google-chrome-extension

我正在做一个小扩展来测试我的apis。但是在制作ajax时会通过错误调用它。

 Refused to load the script 'http://localhost:8080/acton-demouser/user1?callback=jQuery2210009971836116164923_1456851818933&format=json&_=1456851818934' because it violates the following Content Security Policy directive: "default-src 'self' blob: filesystem: chrome-extension-resource:". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

而我的ajax调用网址是:     http://localhost:8080/acton-demouser/user1

manifest.json:

{
  "name": "Ajax Helper",
  "version": "1.0",
  "description": "My first Chrome extension.",
  "manifest_version": 2,
  "browser_action": {
    "default_icon": "icon.png",
    "popup": "popup.html",
    "default_popup": "popup.html"
  },
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "icons": { "16": "icon.png", "128": "icon.png" },
  "content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",
  "permissions": [
    "http://*/*"
  ]
}

js文件: -

$("form").submit(function(){
    var ajaxType = $('#request-method-selector option:selected').val();
    var urlPrefix = 'http://localhost:8080/acton-demo';
    var url = $('#url').val();
    if(ajaxType === 'GET'){
        $.ajax({
            url: (urlPrefix+url),
            error: function() {
                    $('#error').html('<p>An error has occurred</p>');
                },
            dataType: 'jsonp',
            success: function(data) {
                        $("#success").html(data);
                    },
            type: 'GET'
        });
    }

});

我在这里失踪了。

1 个答案:

答案 0 :(得分:1)

您需要将content_security_policy定义的“http://localhost:8080”指定为白名单。因为您在使用$ .ajax调用端点时使用'jsonp'作为dataType。也就是说,它不是Ajax调用,而是一个脚本标记创建。因此,您必须将域添加到content_security_policy定义。

"content_security_policy": "script-src 'self' http://localhost:8080 https://ajax.googleapis.com; object-src 'self'",

基本上,我们可以指定仅具有“https”前缀的网址。但是,为了便于开发,我们可以指定两个域“http://localhost”和“http://127.0.0.1”。这在document

中有所描述