【发布时间】:2021-02-17 15:44:57
【问题描述】:
我有一个 Chrome 扩展程序,可以(如果您允许访问文件 URL)抓取您在 chrome 中打开的本地 pdf 文件并将其发送到我们的 API 进行处理。这是通过从后台脚本获取带有XMLHttpRequest 到file:///Users/user/whatever/testfile.pdf 的pdf 来完成的。
当为 Chrome 扩展迁移到 manifest v3 时,后台脚本变成了一个服务工作者。在服务工作者中,只有fetch 可用,XMLHttpRequest 不可用。问题是,fetch 只支持 http 和 https,不支持 file:// url。那么我怎样才能实现让 Chrome 扩展获取/获取本地文件的相同功能呢?
编辑:我也尝试过的事情:
-
按照答案的建议从注入的 iframe 生成 XMLHttpRequest。 这在发出请求时会出现错误
net:ERR_UNKNOWN_URL_SCHEME -
从注入的内容脚本生成 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 支持承诺)
browser.action.onClicked.addListener(async (tab: Tab) => {
await browser.scripting.executeScript({files: [ "inject.js" ], target: {tabId: tab.id}});
});
【问题讨论】:
标签: google-chrome-extension manifest.json