Noble Polygon
Noble Polygon

Reputation: 806

How to Download a PDF file in the background

How do I download a file in the background of a mobile browser without leaving the current page.

I've taken a look at this StackOverflow post: easiest way to open a download window without navigating away from the page

which works for displaying the file( in this case a pdf) in the same window using this code:

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);

This works fine if you want to display the PDF immediately in the current window.

However, how can you keep the current view and have the file download/display a dialogue showing a download in progress?

The goal is to not open a new tab or window to keep the user engaged with the current page. I've looked through S/O & on the web but haven't found a solution to this. Thanks for any solutions to this issue.

Upvotes: 2

Views: 3507

Answers (1)

jeremy-denis
jeremy-denis

Reputation: 6878

you can use 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.";
  }
}

Upvotes: 3

Related Questions