【问题标题】:XMLHTTPRequest loading local file in chrome extensionXMLHTTPRequest 在 chrome 扩展中加载本地文件
【发布时间】:2019-02-12 10:07:59
【问题描述】:

所以 XMLHttpRequest 不应该用于加载网站的本地文件。如果一个人实际上可以通过 JavaScript 访问用户的文件系统,那将是一个疯狂的安全风险。

但无论出于何种原因,当我使用 XMLHttpRequest 在 chrome 扩展中加载本地文本文件时,它都可以正常工作。 为什么当我在后台脚本中将 XMLHttpRequest 用于 chrome 扩展时,它会加载文件? 这是安全漏洞还是故意的?并且这不会产生与让请求在网页中加载本地文件类似的安全风险吗?

让我尽量用最好的方式解释这一点:

我有一个名为 abc.txt 的文本文件,我想打开它并通过 JavaScript 读取文件内容,因此我决定使用 XMLHttpRequest。

<!DOCTYPE html>
<html>
<body>
<script>
</script>
  <script>
    let txt = '';
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.status == 200 && xmlhttp.readyState == 4){
                txt = xmlhttp.responseText;
                console.log(txt)
            }
    };
    xmlhttp.open("GET", "abc.txt", true);
    xmlhttp.send();
  </script>
</body>
</html>

我得到了通常的错误,test.html:17 Failed to load file:///C:/Users/none/of/your/business/abc.txt: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

但是,当我制作 chrome 扩展时,我可以通过 background.js 脚本加载本地文件。

manifest.js 文件:

{
    "name": "Question",
    "version": "1.0",
    "manifest_version": 2,
    "background": {
        "persistent": true,
        "scripts":["background.js"]
    }
}

background.js 文件:

chrome.runtime.onInstalled.addListener(function() {
    let txt = '';
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.status == 200 && xmlhttp.readyState == 4){
                txt = xmlhttp.responseText;
                console.log(txt)
            }
    };
    xmlhttp.open("GET", "abc.txt", true);
    xmlhttp.send();
});

证明文本文件已加载:

重申我的问题,为什么 XMLHttpRequests 对 chrome 扩展的 background.js 脚本有不同的处理方式?它不会产生与在网页上使用 XMLHttpRequests 类似的问题吗?

注意:XMLHttpRequest 似乎只在 background.js 文件中有效,当我将文件链接到 HTML 文档时,它停止运行并且我收到正常的错误消息。所以我不能在弹出的html文件上运行它。

【问题讨论】:

  • 这是一个示例,表明网络扩展对它们的限制较少
  • 扩展后台脚本允许CORS请求

标签: javascript google-chrome google-chrome-extension xmlhttprequest


【解决方案1】:

根据 Deliaz 的说法,答案是 chrome 允许 CORS 请求。

【讨论】:

    【解决方案2】:

    它只能访问扩展自己目录中的文件。这些文件是扩展的一部分。如果您尝试使用file:// 协议访问其他地方的文件,则会收到错误Not allowed to load local resource。因此,您实际上无法访问用户的文件系统。

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多