我正在开发一个 Chrome 扩展程序,它将文件保存到下载文件夹(这不是它所做的全部,但这是我遇到的问题)。现在我专注于 PDF 文件。基本上,当在 Chrome 中打开 PDF 时,用户可以使用 Menu -> Save File As
手动保存它...,我只是想使用扩展程序自动执行此功能,但我还没有找到了一个很好的方法。
假设我可以检测当前选项卡中是否包含 PDF 文件(基于 this 问题的答案)。
到目前为止,我想到的最好的办法是启动下载:
chrome.downloads.download({
url: tabs[0].url, saveAs: false,
filename: "my file", /* This will be some unique autogenerated identifier */
conflictAction: "overwrite"
});
这可行,但有两个缺点:
- 必须重新下载文件,如果文件很大,这会很痛苦。此外,文件已经下载,我应该可以使用它。
- 出于某种原因,这不适用于本地打开的文件(“file://...”)。它抛出 NETWORK_INVALID_REQUEST 并且不下载。
有没有更好的方法来保存文件?
最佳答案
请注意,chromium/chrome 浏览器似乎将 embed
元素附加到 document.body
以显示 .pdf
文件
a) 利用
window.location.href
检测pdf
,document.querySelectorAll("embed")[0].type
;b) 利用
XMLHttpRequest
请求现有的document
,它应该返回pdf
document
作为blob
响应,来自缓存
;参见console
->Network
->Headers
->Status Code
要允许在 chromium/chrome 浏览器中打开
file:
protocol
,请尝试使用命令行标志--allow-access-from-files
;见How do I make the Google Chrome flag “--allow-file-access-from-files” permanent?
在 .pdf
document
,例如; Ecma-262.pdf尝试
// check if `document` is `pdf`
if (/pdf/i.test(window.location.href.slice(-3))
|| document.querySelectorAll("embed")[0].type === "application/pdf") {
var xhr = new XMLHttpRequest();
// load `document` from `cache`
xhr.open("GET", "", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
if (this.status === 200) {
// `blob` response
console.log(this.response);
var file = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
a.href = file;
a.download = this.response.name
|| document.querySelectorAll("embed")[0].src
.split("/").pop();
document.body.appendChild(a);
a.click();
// remove `a` following `Save As` dialog,
// `window` regains `focus`
window.onfocus = function () {
Array.prototype.forEach.call(document.querySelectorAll("a")
, function (el) {
document.body.removeChild(el)
})
}
};
};
xhr.send();
};
关于javascript - Chrome 扩展程序 - 保存 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114794/