2

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.

Noble Polygon
  • 796
  • 11
  • 36

1 Answers1

3

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.";
  }
}
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35
  • Thanks for your answer. Sorry if this seems like a n00b question (I'm new to using JS), but what should I be doing in the ```pdf_workers.js``` file? – Noble Polygon Jan 20 '20 at 16:38
  • no in fact pdf_workers.js is just the name of the file where the code will be run. the process is : 1) creates a new web worker object 2) runs the code in "demo_workers.js" – jeremy-denis Jan 20 '20 at 16:44