我有一个 Chrome 扩展程序,可以(如果您允许访问文件 URL)抓取您在 Chrome 中打开的本地 pdf 文件,并将其发送到我们的 API 进行处理。这是通过获取 pdf 来完成的XMLHttpRequest
to file:///Users/user/whatever/testfile.pdf
来自后台脚本。
当 Chrome 扩展迁移到清单 v3 时,后台脚本将成为服务工作人员。仅在 Service Worker 中fetch
可用,不可用XMLHttpRequest
。问题是,fetch 仅支持 http 和 https,不支持 file:// url。那么我怎样才能实现让 Chrome 扩展获取/获取本地文件的相同功能呢?
编辑:我也尝试过的事情:
-
Making the XMLHttpRequest from injected iframe as suggested by answer.
This gives error net:ERR_UNKNOWN_URL_SCHEME
when making the request
-
Making the XMLHttpRequest from injected content script.
This gives error 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
用于承诺支持)
browser.action.onClicked.addListener(async (tab: Tab) => {
await browser.scripting.executeScript({files: [ "inject.js" ], target: {tabId: tab.id}});
});