Skip to content

Instantly share code, notes, and snippets.

@jscul
Last active September 19, 2021 04:04
Show Gist options
  • Save jscul/1978a3761496fb5a565454e719ac2415 to your computer and use it in GitHub Desktop.
Save jscul/1978a3761496fb5a565454e719ac2415 to your computer and use it in GitHub Desktop.
Downloads All Images on Page
(async () => {
const QUERY_SELECTOR = "img";
// ! get image blobs
let blobs = [...document.querySelectorAll(QUERY_SELECTOR)].map(
async ({src}) => ({
src,
blob: await (await fetch(src, {mode: "no-cors"})).blob(),
})
);
blobs = await Promise.all(blobs);
// ! skip imports/zip if no images
if (!blobs.length) return;
// ! libraries: JSZip, FileSaver
const cdns = [
`https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js`,
`https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js`,
].map((cdn) => {
const script = document.createElement("script");
script.src = cdn;
document.head.appendChild(script);
return new Promise((res, rej) => {
script.addEventListener("load", () => {
res();
});
});
});
await Promise.all(cdns);
// ! add files to zip
const ext = {
"image/jpeg": "jpg",
"image/png": "png",
};
const zip = new JSZip();
let i = 0;
for (const {blob, src} of blobs) zip.file(`${i++}.${ext[blob.type]}`, blob);
// ! download zip
zip.generateAsync({type: "blob"}).then((content) => {
saveAs(content, "images.zip");
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment