使用沙箱从 Chrome 应用发出 ajax 请求

Making ajax request from Chrome app with sandbox

我尝试从我的 chrome 应用程序中的沙盒页面进行 ajax 调用,但出现此错误:

XMLHttpRequest cannot load https://myserver.com/test. The 'Access-Control-Allow-Origin' header has a value 'https://myserver.com' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.

似乎不​​允许跨域,但在沙盒应用程序中应该.. 哪里错了?

Manifest.json :

{
    "name": "app",
    "description": "app",
    "version": "0.1",
    "manifest_version": 2,
    "permissions": [
        "http://*/*",
        "https://*/*",
        "unlimitedStorage",
        "contextMenus",
        "cookies",
        "tabs",
        "notifications",
        "storage"
    ],
    "sandbox": {
        "pages": [
            "index.html"
        ]
    },
    "app": {
        "background": {
            "scripts": [
                "src/background.js"
            ]
        }
    },
    "icons": {
        "16": "img/favicon.png",
        "128": "img/favicon.png"
    }
}

container.html :

<!DOCTYPE html>
 <html>
 <body>
    <iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-pointer-lock allow-top-navigation" src="index.html" id="MdwSandBox1" width="800px" height="800px"></iframe>
 </body>
 </html>

background.js :

chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('container.html', {
    'bounds': {
      'width': 800,
      'height': 800
    }
  });
});

根据 docs:

A sandboxed page is not subject to the Content Security Policy (CSP) used by the rest of the app or extension (it has its own separate CSP value). This means that, for example, it can use inline script and eval.

但是:

If not specified, the default content_security_policy value is sandbox allow-scripts allow-forms. You can specify your CSP value to restrict the sandbox even further, but it must have the sandbox directive and may not have the allow-same-origin token (see the HTML5 specification for possible sandbox tokens).

所以你无法拨打这个 API 电话。

但是,您可以从应用程序进行 API 调用,然后使用 postMessage 将结果传递给 iframe。 第二种方法是将 required headers 添加到您的后端 - 如果您可以控制它。