如何在后台下载 PDF 文件



如何在不离开当前页面的情况下在移动浏览器的后台下载文件。

我看了这篇StackOverflow帖子:无需离开页面即可打开下载窗口的最简单方法

它用于使用以下代码在同一窗口中显示文件(在本例中为 PDF(:

var file_path = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

如果要立即在当前窗口中显示PDF,则此方法可以正常工作。

但是,如何保持当前视图并使文件下载/显示显示正在进行的下载的对话框?

目标是不打开新的选项卡或窗口来保持用户与当前页面的互动。我已经浏览了S/O和网络上,但没有找到解决方案。感谢您对此问题的任何解决方案。

您可以使用HTML Web worker https://www.w3schools.com/html/html5_webworkers.asp

var w;
function stopWorker() {
w.terminate();
w = undefined;
}
function downloadPDFBackground() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("pdf_workers.js");
}
w.onmessage = function(event) {
var file_path = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
stopWorker();
};
} else {
document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
}
}

最新更新