Chrome 扩展 - 如何使用清单 v3 访问本地文件://

Chrome extension - how to access local file:// with manifest v3

我有一个 Chrome 扩展程序,它可以(如果您允许访问文件 URL)抓取您在 chrome 中打开的本地 pdf 文件并将其发送到我们的 API 进行处理。这是通过从后台脚本中使用 XMLHttpRequestfile:///Users/user/whatever/testfile.pdf 获取 pdf 来完成的。

当为 Chrome 扩展迁移到 manifest v3 时,后台脚本变成了服务工作者。在 service worker 中只有 fetch 可用,而不是 XMLHttpRequest。问题是,fetch 只支持 http 和 https,不支持 file:// urls。那么我怎样才能使 Chrome 扩展名 fetching/getting 成为本地文件的相同功能呢?

编辑:我也尝试过的事情:

  1. 按照答案的建议从注入的 iframe 生成 XMLHttpRequest。 发出请求时会出现错误 net:ERR_UNKNOWN_URL_SCHEME

  2. 从注入的内容脚本生成 XMLHttpRequest。 这给出了错误 Access to XMLHttpRequest at 'file:///.../testfile1.docx.pdf' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

根据我从大量研究中了解到的情况,对 file:// 的访问通常被阻止,而 Chrome 扩展后台脚本曾经是一个例外。在我看来,内容脚本或操作弹出窗口从来不允许这样做。

我的manifest.json供参考:

{
  "manifest_version": 3,
  "name": "..",
  "version": "0.1",
  "icons": {
    "16": "assets/icon-16x16.png",
    "48": "assets/icon-48x48.png",
    "128": "assets/icon-128x128.png"
  },
  "action": {
    "default_title": ".."
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "webRequest",
    "activeTab",
    "scripting",
    "storage",
    "unlimitedStorage",
    "identity",
    "pageCapture"
  ],
  "host_permissions": [
    "<all_urls>"
  ],
  "web_accessible_resources": [{
    "resources": ["iframe.html"],
    "matches": [],
    "extension_ids": []
  }]
}

内容脚本以编程方式注入(使用 webextension-polyfill 支持 promise)

browser.action.onClicked.addListener(async (tab: Tab) => {
  await browser.scripting.executeScript({files: [ "inject.js" ], target: {tabId: tab.id}});
});

Chrome 98岁以上无法在后台service worker中完成,原因你说的。

还有一个 bug 阻止在正常可见的 chrome-extension:// 页面或 iframe 中执行此操作。固定在Chrome91.

解决方案

在Chrome99 and newer中使用fetch
在旧版本中使用以下解决方法。

解决方法 1:文件系统 API、Chrome 86+

ManifestV3 扩展可以使用新的 File System API to read the contents of the file, for example inside the iframe exposed via web_accessible_resources.

解决方法 2. 扩展框架,Chrome91+

使用在带有该 pdf 的选项卡中运行的内容脚本:

    manifest.json 中的
  1. matches 应包含 <all_urls>file://*/* 并且用户应在 chrome://extensions UI 为您的分机。或者你可以使用 activeTab 权限和 programmatic injection 当用户 单击您的扩展图标或通过上下文菜单调用它。
  2. 内容脚本添加了一个不可见的 iframe,指向 web_accessible_resources
  3. 中公开的 iframe.html 文件
  4. iframe.html 加载 iframe.js,它照常使用 XMLHttpRequest。由于 iframe 具有 chrome-extension:// URL 其环境 与您的旧后台脚本相同,因此您可以做任何事情 你之前在那儿做过。

解决方法 3. 扩展 window/tab、Chrome 91+

另一种解决方案是使用您的任何其他可见页面 action 弹出窗口或选项页面或任何其他扩展 chrome-extension:// 属于你的扩展的页面就可以了 像以前一样通过 XMLHttpRequest 访问 file:// URL。

备注

  • 应在此扩展程序的 chrome://extensions 页面中启用文件访问。