10

I'm attempting to write a bookmarklet-like js snippet that can be run from the developer tools console that will provide the src for images in the page:

var x = ["PA633", "PA10", "PA11"];
function nextPage(i) {
    $('#viewport div:first-child').animate({scrollTop: i}, 200);
    i+=1020;
    if (i < 20000) { setTimeout(nextPage, 200, i); }
    for (index = 0; index < $('div.pageImageDisplay img').length; ++index) {
        var page = /&pg=([A-Z]{2,3}\d+)&/.exec($('div.pageImageDisplay img')[index].src);
        if ($.inArray(page[1], x) != -1) {
            x.splice(x.indexOf(page[1]), 1);
            var embiggen = $('div.pageImageDisplay img')[index].src.replace(/&w=\d+$/, "&w=1200");
            console.log(embiggen);
        }
    }
}

This script works in that it provides the correct src links for each image. Is there a way to have javascript download/save each link automatically? It's possible to click on each link (Chrome opens these in a new tab), but somewhat tedious to do so.

The proper way to do it would be to have the javascript snippet save the images to the downloads folder itself, but I have a vague notion this isn't possible. Is it possible, and if so how could that be accomplished?

Please note that this javascript won't be included in a web page directly, but is meant specifically to run from the dev tools console.

John O
  • 4,863
  • 8
  • 45
  • 78

2 Answers2

9

This requires several different parts to work. First off, it's necessary to add (unless you can reuse an existing) link to the page with something like this:

$("body").append($("<a id='xyz'/>"));

Then, you need to set the href of the link to that of the file to be downloaded:

$('#xyz').attr("download", page[1] + ".png");
$('#xyz').attr("href", embiggen);

Note that we can also (within Chrome at least) set the filename automatically, via the download attribute.

Finally, JavaScript can issue a click event to the anchor tag itself with:

$('#xyz')[0].click();

When this runs, it automatically downloads the file. Setting the filename seems to prevent it from popping up the file dialog too.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
John O
  • 4,863
  • 8
  • 45
  • 78
6
$("body").append($("<a id='xyz'/>"));

The above code gave me the following error in some versions of Chrome:

VM42:1 Uncaught DOMException: Failed to execute '$' on 'CommandLineAPI': '<a id='xyz'/>' is not a valid selector. at <anonymous>:1:18

Please try the following code instead, using plain old Javascript.

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 can check the detailed explanation in this answer.

Evan MJ
  • 1,967
  • 13
  • 16
  • 1
    Excellent, thank you! I found that I needed to change the last line to `$('#downloadAnchor')[0].click();` to work. – Y Davis Oct 27 '21 at 01:37