This SO answer details how to download a file via a Chrome Extension, but I am using a Content Script, which has limited access to Chrome's APIs. In other words, I don't have access to the chrome.downloads
object. I also tried this vanilla JS solution, but it did not work for me. Does anyone have a solution for Content Scripts or know why the second solution doesn't work?
2 Answers
Write a background page or event page and do it from there using the example in your linked answer. Communicate from/to the content script with chrome messages.

- 19,571
- 5
- 26
- 36
-
1A working example would be helpful, as I have run into problem after problem trying to get this to work... – Michael Mar 31 '20 at 03:44
If you mean causing a file to be downloaded to the user's computer, this code will work in a Chrome extension content script or in the JS script an a regular webpage:
Firstly, you can cause a file to download without any JS at all by simply adding the "download" attribute to an anchor tag. With this tag, instead of navigating to the URL in the "href" attribute, the URL will be downloaded.
<a href="http://website.com/example_1.txt" download="saved_as_filename.txt" id="downloader">
static download link</a>
To update the URL dynamically:
var theURL = 'http://foo.com/example_2.txt';
$('#downloader').click(function() {
$(this).attr('href',theURL);
});
If you want the download to be initiated by something other than clicking on a link, you can simulate a click on the link. Note that .trigger() won't work for this purpose. Instead you can use document.createEvent:
$('#downloader').css('display','none');
function initiateDownload(someURL) {
theURL = someURL;
var event = document.createEvent("MouseEvent");
event.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
// dispatch event won't work on a jQuery object, so use getElementById
var el = document.getElementById('downloader');
el.dispatchEvent(event);
}
initiateDownload('example_3.txt');

- 528
- 4
- 11
-
2this will NOT work unless the file to be downloaded is in the same domain. it won't work if the file is in a subdomain. Instead, the download attribute will be completely and rudely ignored, even in an extension, and the file will be opened as if the link had been clicked, e.g. replacing the existing window contents. – Michael Mar 31 '20 at 03:06