Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download image link from browser console (javascript)

I'm using Javascript in the Developer Console/Inspect Element (in Firefox and/or Chrome, either one).

I'm wanting to download multiple image files from a link - let's say for example this: https://i.etsystatic.com/9228829/r/il/d729fb/992816422/il_fullxfull.992816422_35w3.jpg

So in the console I have that link (and others) as a string and for each, I'm trying to download them directly to my computer. I can trigger a download, but it either a) open in a new tab instead of downloading, b) downloads an empty image file.

I've tried probably 5 different functions from StackOverflow now but none appear to work. Thoughts?

Example code (found on internet):

function download(filename, filelink){
  var link = document.createElement('a');
  link.href = filelink;
  link.download=true;
  document.body.appendChild(link);
  //link.target = "self";
  link.click();
  console.log(link);
  document.body.removeChild(link);
}

var imageToDownload = "https://i.etsystatic.com/9228829/r/il/d729fb/992816422/il_fullxfull.992816422_35w3.jpg"

download(("image.jpg"), imageToDownload);

Here's a second download function that DOES download, but the file is empty. yes, I'm aware that it's looking for text etc, but I can't modify it to be for images:

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  //element.setAttribute('href', 'data:jpg/image;base64');
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}
like image 827
JackNapier Avatar asked Nov 27 '25 23:11

JackNapier


1 Answers

link.href = filelink;
link.download=true;

The above code will not work. The download attribute of the anchor tag should point to the link where the file to be downloaded is hosted. Only then on clicking the anchor tag the download will be triggered automatically.

Code that works:

var url = 'your url goes here';
var elem = document.createElement('a');
elem.href = url;
elem.download = url;
elem.id="downloadAnchor";
document.body.appendChild(elem);
$('#downloadAnchor').click();

You check the detailed answer in this question

like image 103
Evan MJ Avatar answered Nov 29 '25 14:11

Evan MJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!