Skip to content

Instantly share code, notes, and snippets.

@ImSeaWorld
Created March 20, 2023 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ImSeaWorld/47e179b5d2567fb13677ebced6420ba5 to your computer and use it in GitHub Desktop.
Save ImSeaWorld/47e179b5d2567fb13677ebced6420ba5 to your computer and use it in GitHub Desktop.
Little script to download WordPress images.
class MultiImageDownloader {
constructor(images) {
this.images = images ?? [];
this.downloaded = [];
this.index = 0;
}
downloadFile(url, filename) {
// https://stackoverflow.com/a/45905238/10887412
fetch(url)
.then(response => response.blob())
.then(blob => {
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
})
.catch(console.error);
}
fetch(selector) {
const children = document.querySelectorAll(selector);
for (const img in children) {
if (!children[img].src) continue;
this.images.push(children[img].src);
}
console.log('Fetched ' + this.images.length + ' images.');
}
next(index = -1) {
if (index > -1) {
this.setIndex(index);
}
if (this.index >= this.images.length) {
console.log('Downloaded ' + this.index + ' of ' + this.images.length + ' images. Done!');
return;
}
this.downloadFile(
this.images[this.index].replace(/-\d{3}x\d{3}/s, ''),
this.images[this.index].split('/').pop().replace(/-\d{3}x\d{3}/s, '')
);
this.downloaded.push(this.images[this.index]);
this.index++;
console.log('Downloaded ' + this.index + ' of ' + this.images.length + ' images.');
if (this.index < this.images.length) {
console.log('Next image: ' + this.images[this.index]);
}
}
setIndex(index) {
console.log('Changed index to ' + index + ' from ' + this.index);
this.index = index;
}
downloadAll() {
console.log('Downloading all images... Starting at index ' + this.index + '...');
for (let i = this.index; i < this.images.length; i++) {
this.next(i);
}
if (this.downloaded.length === this.images.length) {
console.log('Downloaded all images.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment