Making a Chrome Extension download a file

Franz Payer picture Franz Payer · Jan 30, 2011 · Viewed 63.1k times · Source

I am creating an extension that will download a mp3 file off a website. I am trying to do this by creating a new tab with the link to the mp3 file, but chrome keeps opening it inside the player instead of downloading it. Is there any way I can create a pop-up to ask the user to "save-as" the file?

Answer

Xan picture Xan · Jun 11, 2014

Fast-forward 3 years, and now Google Chrome offers chrome.downloads API (since Chrome 31).

After declaring "downloads" permission in the manifest, one can initiate a download with this call:

chrome.downloads.download({
  url: "http://your.url/to/download",
  filename: "suggested/filename/with/relative.path" // Optional
});

If you want to generate the file content in the script, you can use Blob and URL APIs, e.g.:

var blob = new Blob(["array of", " parts of ", "text file"], {type: "text/plain"});
var url = URL.createObjectURL(blob);
chrome.downloads.download({
  url: url // The object URL can be used as download URL
  //...
});

For more options (i.e. Save As dialog, overwriting existing files, etc.), see the documentation.