0

I'm making an extension in which the user is setting some configs and, based on his selection, a png file needs to be downloaded (from a remote url) in the background and saved as a file somewhere to make it accessible later. It must be saved as a file and also injected in the page by it's final path.

Reading the [fileSystem][1] api of chrome, all methods are sending a prompt to the user in order to download a file. Is there any way I can save files to a location without prompting the user for download?

Romeo Mihalcea
  • 9,714
  • 12
  • 50
  • 102
  • Download as blob with `fetch`, then save via `a` link with `download` attribute e.g. [JavaScript blob filename without link](//stackoverflow.com/a/19328891) and use the object url on the page. – wOxxOm Apr 19 '17 at 18:24
  • Any way I could do that in the `background.js` file without having to deal with the dom at all? – Romeo Mihalcea Apr 19 '17 at 19:34
  • 1
    I guess yes, why not? The background page is just like any other page and has its own DOM. – wOxxOm Apr 19 '17 at 19:35

1 Answers1

0

In an effort to close this years old question, I'm quoting and expanding on wOxxOm's comments and posting as an answer.

The key is to download the raw data as a blob type using fetch. You can then save it via an anchor tag (a link) using the download attribute. You can simulate the "click" on the link using JavaScript if you need to keep it in the background.

Here's an example (more or less copied another SO post).

const data = ''; // Your binary image data
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
const blob = new Blob([data], {type: "octet/stream"}),
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName; // Optional
a.click();
window.URL.revokeObjectURL(url);

This is not without its faults. For instance, it works best with small file sizes (exact size varies by browser, typically ~2MB max). The download attribute requires HTML5 support.

CyberEd
  • 875
  • 9
  • 19