2

I'm trying to download some object in the page from console. But it only save when I=3(last iteration), I think the problem may be the need to wait for downloads, but idk how to solve it.

First, the elements are render by canvas, so I turn them to image format. Then, turn them into element, and click it to download.

I use the way in How to save a base64 image to user's disk using JavaScript?

But it only work in last iteration... any help? much thanks.

for(let i=1;i<=3;i++){
    // load image
    item_id = 'page'+i;
    document.getElementById(item_id)
    let image = document.getElementById(item_id).toDataURL("image/png").replace("image/png", "image/octet-stream");

    // download image
    var link = document.createElement("a");
    document.body.appendChild(link);
    link.setAttribute("href", image);
    link.setAttribute("download", item_id+'.png');
    link.click();
}
Toby Ya
  • 21
  • 2
  • 1
    Does `const link` instead of `var link` help? – Sebastian Simon Oct 04 '21 at 04:17
  • ohh that works. Is it because it is repeatedly generated, so it is not refreshed? – Toby Ya Oct 04 '21 at 06:11
  • `var` is function-scoped, so `var link` is a single variable, accessible outside the loop. `const`, however, is block-scoped, so each `const link` will be a separate variable in its own scope. I assume there’s something asynchronous going on with the download dialog, so by the time the dialog shows, the `for` loop is finished, and `var link` is set to the last link, though I can’t really explain what’s going on, specifically. Related: [Closure inside loops](/q/750486/4642212). Not sure why you’re mixing `let` and `var` like this… It should also be `const image`. Which browser are you using? – Sebastian Simon Oct 04 '21 at 06:21
  • I am using safari and Firefox. I didn't notice this effect on the domain-wide variables, after using that, it works on Firefox, but not safari. I think this is about the download mechanism in safari (download too much at the same time? ), so it should be fine. – Toby Ya Oct 05 '21 at 03:13

0 Answers0