javascript - Chrome 扩展程序 - 保存 PDF 文件

标签 javascript google-chrome pdf google-chrome-extension

我正在开发一个 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 文件

  1. a) 利用 window.location.href 检测 pdf , document.querySelectorAll("embed")[0].type;

    b) 利用XMLHttpRequest请求现有的document,它应该返回pdf document作为blob 响应,来自缓存;参见 console -> Network -> Headers -> Status Code

  2. 要允许在 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/

相关文章:

javascript - 什么可能是 javascript 中 iteritems() [来自 python] 的替代品

javascript - Google Chrome/Chromium 扩展程序中的键盘快捷键

javascript - 将 subview 附加到与父 View 相同的 block

javascript - Chrome 上不一致/延迟的 HTML5 桌面推送通知

javascript - jssor : bug in full-width-slider. html

google-chrome - 删除 chrome 中 dojo 按钮上的黄色边框

pdf - Coldfusion:CFDocument PDF 替代品

c# - 使用 PDFSharp-gdi C# 将 Tiff 转换为 pdf

javascript - 如何检测 PDF 是否在 Chrome pdf 查看器中打开

javascript - 将变量传递给 JavaScript 函数