简体   繁体   中英

Javascript: auto-download file when link “clicked”

I found a similar question, posted in an older topic, but the answer given there did not work. I am testing with Mozilla Firefox browser (latest version).

I have an array with imageLinks, and want to auto-trigger a download without user interaction. my code is given below:

for (var i=0; i<imageLinks.length; i++) {

if (imageLinks[i]) {

    console.log(imageLinks[i]);
    var link = document.createElement('a');
    link.href = imageLinks[i];
    link.download = 'imagefile';
    link.click();
    }
}

However, in Forefox the images are opening in new tabs?

I stumbled upon this snippet on a forum, and it seems to do the trick. Note however that the browser will still ask the user whether s/he wants the file(s) to be saved, and where. This query can be accepted as "automatically do this with files of this type", and from then onwards the downloads will be automatically saved to the local drive.

function simulateClick() {
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);
    var a = document.getElementById('myLink');
    a.dispatchEvent(evt);
  }

This function can be called on the array with image links, and the user selected images can be saved to the drive. I am happy with this solution, since it's easier to implement than a ZIP-file with user selected images. The image galleries are small, so the downloads should be initialized rather quick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM