javascript - 使用沙箱从 Chrome 应用程序发出 ajax 请求

标签 javascript google-chrome google-chrome-extension google-chrome-app

我尝试从 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"
    }
}

容器.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>

背景.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到您的后端 - 如果您可以控制它。

关于javascript - 使用沙箱从 Chrome 应用程序发出 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28562630/

相关文章:

javascript - 如何导出模块中的函数?

android - Chrome ADB 扩展不适用于 Debian 7

javascript - 为所有浏览器选项卡设置 Cookie

javascript - 如何通过扩展为 javascript 代码提供额外的功能?

javascript - 如何在 JavaScript 中编写 Date 对象?

javascript - 在更改功能上使用 jQuery 设置标签

javascript - Chrome 扩展程序阻止 google.co.uk

javascript - 如何在 Chrome 中启用屏幕/桌面捕获?

javascript - 正则表达式匹配 : Surrounded by space or start of line, 但不匹配

javascript - 如何在 chrome 扩展开发中获取选定的文本?