Can javascript in the dev tools console download/save files, or is this sandboxed?

John O picture John O · Jul 29, 2015 · Viewed 11.8k times · Source

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.

Answer

John O picture John O · Jul 29, 2015

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.