Media ZIP Grabber added to the hub
Grab images, GIFs and videos from any page in a full-screen grid. Save one at a time or all as a ZIP.
$ run media-zip-grabber
working on it…
✓ all done
Open the page with the images, GIFs or videos.
Open the console: F12 or Ctrl+Shift+J on Windows, Cmd+Option+J on Mac. Chrome may ask you to type allow pasting first.
Copy the script below, paste it into the console and press Enter. Choose Images, GIFs or Videos at the top, then use the download button on a card or select several and press Download ZIP.
The full script is below. Copy it in one click or download the file. Nothing is minified or hidden.
(async () => {
const OPTIONS = {
minSize: 60,
defaultQuality: "full",
defaultKinds: ["image", "gif", "video"],
batchSize: 60,
maxCandidates: 8,
autoLoadOnStart: false,
maxLoadRounds: 40,
idleRoundsToStop: 3,
waitAfterLoadMs: 1500,
concurrency: 6,
probeConcurrency: 8,
probeTimeoutMs: 15000,
quality: 0.95,
minImagesForArea: 4,
};
const HOST_ID = "zn-image-grabber";
const SITE = (location.hostname || "page").replace(/^www\./, "");
window.__znImageGrabberCleanup?.();
const log = (...args) => {
console.log("%c[IMAGE-ZIP]", "color:#10a37f;font-weight:bold", ...args);
};
const sleep = (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
const IMAGE_EXT = /\.(jpe?g|jfif|png|apng|gif|webp|avif|svg|bmp|ico|tiff?|heic)(?:$|[?#])/i;
const VIDEO_EXT = /\.(mp4|m4v|webm|mov|ogv)(?:$|[?#])/i;
const STREAM_EXT = /\.(m3u8|mpd|m4s|ts)(?:$|[?#])/i;
const NOT_IMAGE_EXT = /\.(css|js|mjs|json|woff2?|ttf|otf|eot|html?)(?:$|[?#])/i;
const PLACEHOLDER = /placeholder|blank\.(gif|png)|spacer\.gif|transparent\.(gif|png)|pixel\.gif|1x1\.(gif|png)/i;
const HD_ATTRS = [
"data-zoom-image",
"data-zoom-src",
"data-large",
"data-large-src",
"data-large_image",
"data-full",
"data-full-src",
"data-hires",
"data-highres",
"data-original-src",
];
const SRCSET_ATTRS = ["data-srcset", "data-lazy-srcset"];
const LAZY_ATTRS = ["data-src", "data-original", "data-lazy-src", "data-lazy", "data-url", "data-image", "data-bg", "data-background", "data-bg-src"];
const SKIP_TAGS = new Set(["script", "style", "link", "meta", "source", "iframe", "noscript", "template"]);
const TYPES = ["jpg", "png", "webp", "gif", "svg", "avif", "mp4", "webm", "mov", "ogv", "other"];
const VIDEO_TYPES = new Set(["mp4", "webm", "mov", "ogv"]);
const KINDS = [
["image", "Images"],
["gif", "GIFs"],
["video", "Videos"],
];
const MIME = {
mp4: "video/mp4",
webm: "video/webm",
mov: "video/quicktime",
ogv: "video/ogg",
jpg: "image/jpeg",
png: "image/png",
webp: "image/webp",
gif: "image/gif",
avif: "image/avif",
svg: "image/svg+xml",
bmp: "image/bmp",
ico: "image/x-icon",
heic: "image/heic",
};
const LOAD_MORE_TEXT = /^\s*(load|show|view|see)\s+more\b|^\s*more\s*$|aur\s+dekh|mazeed|next\s+page/i;
const CLICKABLE_SELECTOR = "button, [role='button'], a, input[type='button'], input[type='submit']";
const AREA_IMAGE_SELECTOR = "img, picture, video, [data-src], [data-bg], [data-background], [style*='background']";
const items = new Map();
const variants = new Set();
const selected = new Set();
let nextOrder = 0;
const toAbsolute = (raw) => {
if (!raw || typeof raw !== "string") {
return null;
}
const value = raw.trim();
if (!value || value.startsWith("blob:") || value.startsWith("javascript:")) {
return null;
}
if (value.startsWith("data:")) {
return /^data:image\//i.test(value) ? value : null;
}
try {
const url = new URL(value, location.href);
return /^https?:$/.test(url.protocol) ? url.href : null;
} catch {
return null;
}
};
const toAbsoluteMedia = (raw) => {
if (typeof raw === "string" && /^data:video\//i.test(raw.trim())) {
return raw.trim();
}
const url = toAbsolute(raw);
return url ? url.replace(/#t=[^#]*$/, "") : null;
};
const isPlaceholder = (url) => {
return (url.startsWith("data:") && url.length < 400) || PLACEHOLDER.test(url);
};
const markVariant = (raw) => {
const url = toAbsolute(raw);
if (url) {
variants.add(url);
}
};
const nextImageInner = (url) => {
try {
const parsed = new URL(url);
const inner = /\/_next\/image\/?$/.test(parsed.pathname) && parsed.searchParams.get("url");
return inner ? new URL(inner, location.href).href : null;
} catch {
return null;
}
};
const extensionOf = (url) => {
const dataMatch = url.match(/^data:image\/([\w+.-]+)/i);
if (dataMatch) {
return dataMatch[1];
}
const target = nextImageInner(url) || url;
let pathExt = "";
try {
pathExt = (new URL(target).pathname.match(/\.(\w{2,5})$/) || [])[1] || "";
} catch {
pathExt = "";
}
if (pathExt) {
return pathExt;
}
const queryExt = target.match(/[?&](?:format|fm|ext|type)=(\w+)/i);
return queryExt ? queryExt[1] : "";
};
const typeFromUrl = (url) => {
const ext = extensionOf(url).toLowerCase();
if (["jpeg", "jpg", "jfif", "pjpeg"].includes(ext)) {
return "jpg";
}
if (ext === "svg+xml") {
return "svg";
}
if (ext === "apng") {
return "png";
}
if (ext === "m4v") {
return "mp4";
}
if (ext === "quicktime") {
return "mov";
}
return TYPES.includes(ext) ? ext : "other";
};
const kindFor = (source, type) => {
if (source === "video" || VIDEO_TYPES.has(type)) {
return "video";
}
return type === "gif" ? "gif" : "image";
};
const SIZE_SUFFIX = /-\d{2,5}x\d{2,5}(?=\.\w{3,4}$)/;
const SHOP_SUFFIX = /_(?:\d{2,5}x\d{0,5}|x\d{2,5}|pico|icon|thumb|small|compact|medium|large|grande)(?=(?:@\dx)?\.\w{3,4}$)/i;
const SIZE_PARAMS = [
"w",
"h",
"width",
"height",
"resize",
"size",
"fit",
"crop",
"dpr",
"q",
"quality",
"imwidth",
"imheight",
"maxwidth",
"maxheight",
"max-w",
"max-h",
"sw",
"sh",
"tr",
];
const withPath = (parsed, path) => {
if (path === parsed.pathname) {
return null;
}
const copy = new URL(parsed.href);
copy.pathname = path;
return copy.href;
};
const withParam = (parsed, key, value) => {
const copy = new URL(parsed.href);
copy.searchParams.set(key, value);
return copy.href === parsed.href ? null : copy.href;
};
const withoutParams = (parsed, keys) => {
const copy = new URL(parsed.href);
keys.forEach((key) => copy.searchParams.delete(key));
return copy.href === parsed.href ? null : copy.href;
};
const hostIs = (parsed, pattern) => {
return pattern.test(parsed.hostname);
};
const HD_RULES = [
(u) => withPath(u, u.pathname.replace(SIZE_SUFFIX, "")),
(u) => withPath(u, u.pathname.replace(/-scaled(?=\.\w{3,4}$)/, "")),
(u) => withPath(u, u.pathname.replace(SHOP_SUFFIX, "")),
(u) => (hostIs(u, /wikimedia\.org$/) && u.pathname.includes("/thumb/") ? withPath(u, u.pathname.replace("/thumb/", "/").replace(/\/[^/]+$/, "")) : null),
(u) => (hostIs(u, /pinimg\.com$/) ? withPath(u, u.pathname.replace(/^\/\d+x\d*\//, "/originals/")) : null),
(u) => (hostIs(u, /googleusercontent\.com$|ggpht\.com$/) ? withPath(u, u.pathname.replace(/=[swh]\d+[^/]*$/, "=s0")) : null),
(u) => (hostIs(u, /media-amazon\.com$|images-amazon\.com$/) ? withPath(u, u.pathname.replace(/\._[^/]*_\.(?=\w{3,4}$)/, ".")) : null),
(u) => (hostIs(u, /etsystatic\.com$/) ? withPath(u, u.pathname.replace(/il_\d+x[\dN]+/, "il_fullxfull")) : null),
(u) => (hostIs(u, /ebayimg\.com$/) ? withPath(u, u.pathname.replace(/s-l\d+/, "s-l1600")) : null),
(u) => (u.hostname === "pbs.twimg.com" ? withParam(u, "name", "orig") : null),
(u) => (hostIs(u, /cloudinary\.com$/) ? withPath(u, u.pathname.replace(/\/upload\/(?:[a-z]{1,3}_[^/]+\/)+/, "/upload/")) : null),
(u) => (hostIs(u, /wixstatic\.com$/) ? withPath(u, u.pathname.replace(/\/v1\/.*$/, "")) : null),
(u) => (/^\d+w$/.test(u.searchParams.get("format") || "") ? withParam(u, "format", "original") : null),
(u) => withoutParams(u, SIZE_PARAMS),
];
const guessBigger = (url) => {
if (url.startsWith("data:")) {
return [];
}
const inner = nextImageInner(url);
const bases = inner ? [inner, url] : [url];
const out = inner ? [inner] : [];
bases.forEach((base) => {
let parsed;
try {
parsed = new URL(base);
} catch {
return;
}
HD_RULES.forEach((rule) => {
try {
const candidate = rule(parsed);
if (candidate && candidate !== url && !out.includes(candidate)) {
out.push(candidate);
}
} catch {
return;
}
});
});
return out;
};
const addItem = (url, el, source, alt = "", hdUrls = [], preview = null) => {
if (!url || isPlaceholder(url) || STREAM_EXT.test(url)) {
return;
}
let item = items.get(url);
if (!item) {
nextOrder += 1;
const previewUrl = preview && !isPlaceholder(preview) ? preview : url;
const type = typeFromUrl(url);
const kind = kindFor(source, type);
item = { url, preview: previewUrl, source, kind, alt: "", hd: [], els: new Set(), type, w: 0, h: 0, duration: 0, order: nextOrder };
items.set(url, item);
selected.add(item);
if (kind !== "video") {
guessBigger(url).forEach((candidate) => hdUrls.push(candidate));
}
}
if (el) {
item.els.add(el);
}
if (alt && !item.alt) {
item.alt = alt.trim().slice(0, 140);
}
hdUrls.forEach((candidate) => {
if (candidate && candidate !== url && !item.hd.includes(candidate)) {
item.hd.push(candidate);
variants.add(candidate);
}
});
};
const parseSrcset = (srcset) => {
const out = [];
let rest = srcset || "";
while (rest.trim()) {
rest = rest.replace(/^[\s,]+/, "");
const urlMatch = rest.match(/^\S+/);
if (!urlMatch) {
break;
}
let url = urlMatch[0];
rest = rest.slice(url.length);
let descriptor = "";
if (/,+$/.test(url)) {
url = url.replace(/,+$/, "");
} else {
const end = rest.indexOf(",");
descriptor = (end === -1 ? rest : rest.slice(0, end)).trim();
rest = end === -1 ? "" : rest.slice(end + 1);
}
out.push({ url, score: Number.parseFloat(descriptor) || 1 });
}
return out.sort((a, b) => b.score - a.score);
};
const bestFromSrcsetFamily = (img) => {
const picture = img.parentElement?.tagName === "PICTURE" ? img.parentElement : null;
const sets = [img.getAttribute("srcset")];
if (picture) {
picture.querySelectorAll("source").forEach((source) => sets.push(source.getAttribute("srcset")));
}
const parsed = sets
.filter(Boolean)
.map(parseSrcset)
.filter((list) => list.length);
parsed.forEach((list) => list.forEach((candidate) => markVariant(candidate.url)));
const current = img.currentSrc;
const family = parsed.find((list) => list.some((candidate) => toAbsolute(candidate.url) === current));
const fallback = picture ? null : parsed[0];
const chosen = family || fallback;
return chosen ? chosen[0].url : null;
};
const linkedImage = (el) => {
const link = el.closest("a[href]");
const href = link?.getAttribute("href") || "";
return IMAGE_EXT.test(href) ? toAbsolute(href) : null;
};
const scanImg = (img) => {
const candidates = [
...HD_ATTRS.map((attr) => img.getAttribute(attr)),
bestFromSrcsetFamily(img),
...SRCSET_ATTRS.map((attr) => parseSrcset(img.getAttribute(attr))[0]?.url),
...LAZY_ATTRS.map((attr) => img.getAttribute(attr)),
img.currentSrc,
img.getAttribute("src"),
];
markVariant(img.currentSrc);
markVariant(img.getAttribute("src"));
const chosen = candidates.map(toAbsolute).find((url) => url && !isPlaceholder(url));
const linked = linkedImage(img);
addItem(chosen, img, "img", img.alt || img.title, linked ? [linked] : [], toAbsolute(img.currentSrc));
};
const scanLink = (link) => {
const href = link.getAttribute("href") || "";
if (VIDEO_EXT.test(href)) {
addItem(toAbsolute(href), link, "video", link.title || link.innerText);
} else if (IMAGE_EXT.test(href) && !link.querySelector("img")) {
addItem(toAbsolute(href), link, "link", link.title || link.innerText);
}
};
const streamingVideos = new Set();
const videoSource = (video) => {
const sources = [...video.querySelectorAll("source")].filter((source) => {
const type = source.getAttribute("type");
return !type || video.canPlayType(type) !== "";
});
const candidates = [video.currentSrc, video.getAttribute("src"), ...sources.map((source) => source.getAttribute("src")), video.getAttribute("data-src")];
return candidates.map(toAbsoluteMedia).find(Boolean);
};
const scanVideo = (video) => {
const poster = toAbsolute(video.getAttribute("poster"));
addItem(poster, video, "poster");
const url = videoSource(video);
if (url) {
addItem(url, video, "video", video.title || video.getAttribute("aria-label") || "");
const item = items.get(url);
if (item && poster && !item.poster) {
item.poster = poster;
}
} else if ((video.currentSrc || "").startsWith("blob:")) {
streamingVideos.add(video);
}
};
const scanLazyAttrs = (el) => {
[...HD_ATTRS, ...LAZY_ATTRS].forEach((attr) => {
const url = toAbsolute(el.getAttribute(attr));
if (url && (url.startsWith("data:") || IMAGE_EXT.test(url))) {
addItem(url, el, "lazy");
}
});
};
const addCssUrls = (cssValue, el) => {
if (!cssValue || cssValue === "none" || !cssValue.includes("url(")) {
return;
}
for (const match of cssValue.matchAll(/url\(\s*(['"]?)(.*?)\1\s*\)/g)) {
const url = toAbsolute(match[2]);
if (url && !NOT_IMAGE_EXT.test(url)) {
addItem(url, el, "css");
}
}
};
const scanStyles = (el) => {
addCssUrls(el.getAttribute("style"), el);
const computed = getComputedStyle(el);
addCssUrls(computed.backgroundImage, el);
addCssUrls(computed.borderImageSource, el);
["::before", "::after"].forEach((pseudo) => {
const pseudoStyle = getComputedStyle(el, pseudo);
addCssUrls(pseudoStyle.backgroundImage, el);
addCssUrls(pseudoStyle.content, el);
});
};
const scanElement = (el) => {
const tag = el.tagName.toLowerCase();
if (SKIP_TAGS.has(tag)) {
return;
}
if (tag === "img") {
scanImg(el);
} else if (tag === "a") {
scanLink(el);
} else if (tag === "video") {
scanVideo(el);
} else if (tag === "image") {
addItem(toAbsolute(el.getAttribute("href") || el.getAttribute("xlink:href")), el, "svg");
} else if (tag === "input" && el.type === "image") {
addItem(toAbsolute(el.getAttribute("src")), el, "img");
} else {
scanLazyAttrs(el);
}
scanStyles(el);
};
const collectElements = (root, bucket) => {
root.querySelectorAll("*").forEach((el) => {
if (el.id === HOST_ID) {
return;
}
bucket.push(el);
if (el.shadowRoot) {
collectElements(el.shadowRoot, bucket);
}
});
return bucket;
};
const scanMeta = () => {
document.querySelectorAll("meta[property='og:image'], meta[name='twitter:image'], link[rel='image_src']").forEach((el) => {
addItem(toAbsolute(el.getAttribute("content") || el.getAttribute("href")), null, "meta");
});
document.querySelectorAll("meta[property='og:video'], meta[property='og:video:url'], meta[property='og:video:secure_url']").forEach((el) => {
const url = toAbsoluteMedia(el.getAttribute("content"));
if (url && VIDEO_EXT.test(url)) {
addItem(url, null, "video");
}
});
};
const scanNetwork = () => {
performance.getEntriesByType("resource").forEach((entry) => {
const url = entry.name.replace(/#t=[^#]*$/, "");
if (variants.has(url) || items.has(url) || NOT_IMAGE_EXT.test(url)) {
return;
}
if (entry.initiatorType === "video" || VIDEO_EXT.test(url)) {
addItem(toAbsoluteMedia(url), null, "video");
return;
}
const imageLike = entry.initiatorType === "img" || entry.initiatorType === "css" || IMAGE_EXT.test(url);
if (imageLike) {
addItem(toAbsolute(url), null, "network");
}
});
};
const scanPage = () => {
collectElements(document, []).forEach(scanElement);
scanMeta();
scanNetwork();
};
const isOnScreen = (el) => {
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0 && !el.disabled;
};
const staysOnPage = (el) => {
if (el.tagName.toLowerCase() !== "a") {
return true;
}
const href = (el.getAttribute("href") || "").trim();
return !href || href.startsWith("#") || href.startsWith("javascript:");
};
const findLoadMoreButton = () => {
return [...document.querySelectorAll(CLICKABLE_SELECTOR)].find((el) => {
const label = el.innerText || el.value || el.getAttribute("aria-label") || "";
return LOAD_MORE_TEXT.test(label) && isOnScreen(el) && staysOnPage(el);
});
};
const scrollEverythingDown = () => {
window.scrollTo(0, document.documentElement.scrollHeight);
document.querySelectorAll("*").forEach((el) => {
const style = getComputedStyle(el);
const scrollable = /(auto|scroll)/.test(style.overflowY) && el.scrollHeight > el.clientHeight + 50;
if (scrollable) {
el.scrollTop = el.scrollHeight;
}
});
};
const sniffType = (bytes) => {
if (bytes.length < 12) {
return null;
}
const ascii = (start, end) => String.fromCharCode(...bytes.slice(start, Math.min(end, bytes.length)));
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
return "jpg";
}
if (bytes[0] === 0x89 && ascii(1, 4) === "PNG") {
return "png";
}
if (ascii(0, 4) === "GIF8") {
return "gif";
}
if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP") {
return "webp";
}
if (ascii(4, 8) === "ftyp") {
const brands = ascii(8, 40);
if (/avi[fs]/.test(brands)) {
return "avif";
}
if (/hei[cxs]|mif1/.test(brands)) {
return "heic";
}
return brands.startsWith("qt ") ? "mov" : "mp4";
}
if (bytes[0] === 0x1a && bytes[1] === 0x45 && bytes[2] === 0xdf && bytes[3] === 0xa3) {
return "webm";
}
if (ascii(0, 4) === "OggS") {
return "ogv";
}
if (ascii(0, 2) === "BM") {
return "bmp";
}
if (bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 1 && bytes[3] === 0) {
return "ico";
}
const head = new TextDecoder().decode(bytes.slice(0, 2048)).trimStart().toLowerCase();
const svgStart = ["<svg", "<?xml", "<!--", "<!doctype svg"].some((start) => head.startsWith(start));
return svgStart && head.includes("<svg") ? "svg" : null;
};
const fetchBytes = async (url) => {
const sameOrigin = url.startsWith("data:") || new URL(url).origin === location.origin;
const attempt = async (credentials, cache) => {
const response = await fetch(url, { credentials, mode: "cors", cache });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return new Uint8Array(await response.arrayBuffer());
};
if (sameOrigin) {
return attempt("include", "force-cache");
}
const tries = [
["omit", "force-cache"],
["omit", "reload"],
["include", "reload"],
];
for (const [credentials, cache] of tries) {
try {
return await attempt(credentials, cache);
} catch (err) {
if (err.message.startsWith("HTTP")) {
throw err;
}
}
}
throw new Error("Blocked by CORS (the other site does not allow downloading this file)");
};
const webpSize = (bytes, view) => {
const chunk = String.fromCharCode(...bytes.slice(12, 16));
if (chunk === "VP8X") {
return { w: 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16)), h: 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16)) };
}
if (chunk === "VP8L") {
return {
w: 1 + (((bytes[22] & 0x3f) << 8) | bytes[21]),
h: 1 + (((bytes[24] & 0x0f) << 10) | (bytes[23] << 2) | ((bytes[22] & 0xc0) >> 6)),
};
}
if (chunk === "VP8 ") {
return { w: view.getUint16(26, true) & 0x3fff, h: view.getUint16(28, true) & 0x3fff };
}
return null;
};
const JPEG_SOF = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
const jpegSize = (bytes, view) => {
let pos = 2;
while (pos + 9 < bytes.length) {
if (bytes[pos] !== 0xff) {
pos += 1;
continue;
}
const marker = bytes[pos + 1];
if (marker === 0xff || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) {
pos += marker === 0xff ? 1 : 2;
continue;
}
if (JPEG_SOF.has(marker)) {
return { w: view.getUint16(pos + 7), h: view.getUint16(pos + 5) };
}
pos += 2 + view.getUint16(pos + 2);
}
return null;
};
const headerSize = (bytes, kind) => {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
try {
if (kind === "png") {
return { w: view.getUint32(16), h: view.getUint32(20) };
}
if (kind === "gif") {
return { w: view.getUint16(6, true), h: view.getUint16(8, true) };
}
if (kind === "jpg") {
return jpegSize(bytes, view);
}
if (kind === "webp") {
return webpSize(bytes, view);
}
return null;
} catch {
return null;
}
};
const imageSize = async (bytes, kind) => {
if (VIDEO_TYPES.has(kind)) {
return { w: 0, h: 0 };
}
const fromHeader = headerSize(bytes, kind);
if (fromHeader && fromHeader.w && fromHeader.h) {
return fromHeader;
}
try {
const bitmap = await createImageBitmap(new Blob([bytes], { type: MIME[kind] }));
const size = { w: bitmap.width, h: bitmap.height };
bitmap.close();
return size;
} catch {
return { w: 0, h: 0 };
}
};
const candidatesFor = (item, quality) => {
if (quality !== "full") {
return [item.url];
}
return [...new Set([...item.hd, item.url])].slice(0, OPTIONS.maxCandidates);
};
const isBigger = (next, best) => {
if (!best) {
return true;
}
if (next.area !== best.area) {
return next.area > best.area;
}
return next.bytes.length > best.bytes.length;
};
const fetchBest = async (item, quality) => {
let best = null;
let lastError = new Error("download failed");
for (const url of candidatesFor(item, quality)) {
try {
const bytes = await fetchBytes(url);
const kind = sniffType(bytes);
if (!kind) {
throw new Error("the file received is not an image");
}
const size = await imageSize(bytes, kind);
const next = { bytes, kind, url, w: size.w, h: size.h, area: kind === "svg" ? Infinity : size.w * size.h };
if (isBigger(next, best)) {
best = next;
}
} catch (err) {
lastError = err;
}
}
if (!best) {
throw lastError;
}
return best;
};
const decodeImage = async (blob) => {
try {
return await createImageBitmap(blob);
} catch {
const objectUrl = URL.createObjectURL(blob);
setTimeout(() => URL.revokeObjectURL(objectUrl), 20_000);
const img = new Image();
img.src = objectUrl;
await img.decode();
return img;
}
};
const convertImage = async (file, target) => {
if (target === "original" || target === file.kind) {
return file;
}
const source = await decodeImage(new Blob([file.bytes], { type: MIME[file.kind] }));
const canvas = document.createElement("canvas");
canvas.width = source.width || source.naturalWidth || 1024;
canvas.height = source.height || source.naturalHeight || 1024;
const context = canvas.getContext("2d");
if (target === "jpg") {
context.fillStyle = "#ffffff";
context.fillRect(0, 0, canvas.width, canvas.height);
}
context.drawImage(source, 0, 0, canvas.width, canvas.height);
const blob = await new Promise((resolve, reject) => {
canvas.toBlob((result) => (result ? resolve(result) : reject(new Error("conversion failed"))), MIME[target], OPTIONS.quality);
});
const bytes = new Uint8Array(await blob.arrayBuffer());
return { bytes, kind: sniffType(bytes) || target, url: file.url };
};
const buildCrcTable = () => {
const table = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) {
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
}
table[i] = c >>> 0;
}
return table;
};
const CRC_TABLE = buildCrcTable();
const crc32 = (bytes) => {
let c = 0xffffffff;
for (let i = 0; i < bytes.length; i++) {
c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
}
return (c ^ 0xffffffff) >>> 0;
};
const dosDateTime = (date) => {
const time = (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2);
const day = ((date.getFullYear() - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
return { time, day };
};
const ZIP_VERSION = 20;
const UTF8_FLAG = 0x0800;
const STORE_METHOD = 0;
const localHeader = (entry, stamp) => {
const view = new DataView(new ArrayBuffer(30));
view.setUint32(0, 0x04034b50, true);
view.setUint16(4, ZIP_VERSION, true);
view.setUint16(6, UTF8_FLAG, true);
view.setUint16(8, STORE_METHOD, true);
view.setUint16(10, stamp.time, true);
view.setUint16(12, stamp.day, true);
view.setUint32(14, entry.crc, true);
view.setUint32(18, entry.data.length, true);
view.setUint32(22, entry.data.length, true);
view.setUint16(26, entry.nameBytes.length, true);
return new Uint8Array(view.buffer);
};
const centralHeader = (entry, stamp) => {
const view = new DataView(new ArrayBuffer(46));
view.setUint32(0, 0x02014b50, true);
view.setUint16(4, ZIP_VERSION, true);
view.setUint16(6, ZIP_VERSION, true);
view.setUint16(8, UTF8_FLAG, true);
view.setUint16(10, STORE_METHOD, true);
view.setUint16(12, stamp.time, true);
view.setUint16(14, stamp.day, true);
view.setUint32(16, entry.crc, true);
view.setUint32(20, entry.data.length, true);
view.setUint32(24, entry.data.length, true);
view.setUint16(28, entry.nameBytes.length, true);
view.setUint32(42, entry.offset, true);
return new Uint8Array(view.buffer);
};
const endRecord = (count, centralSize, centralOffset) => {
const view = new DataView(new ArrayBuffer(22));
view.setUint32(0, 0x06054b50, true);
view.setUint16(8, count, true);
view.setUint16(10, count, true);
view.setUint32(12, centralSize, true);
view.setUint32(16, centralOffset, true);
return new Uint8Array(view.buffer);
};
const buildZip = (files) => {
const stamp = dosDateTime(new Date());
const encoder = new TextEncoder();
const localParts = [];
const centralParts = [];
let offset = 0;
for (const file of files) {
const entry = { data: file.data, nameBytes: encoder.encode(file.name), crc: crc32(file.data), offset };
localParts.push(localHeader(entry, stamp), entry.nameBytes, entry.data);
centralParts.push(centralHeader(entry, stamp), entry.nameBytes);
offset += 30 + entry.nameBytes.length + entry.data.length;
}
const centralSize = centralParts.reduce((sum, part) => sum + part.length, 0);
return [...localParts, ...centralParts, endRecord(files.length, centralSize, offset)];
};
const saveBlob = (blob, fileName) => {
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = fileName;
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(link.href), 60_000);
};
let inlineCount = 0;
const baseNameFor = (url) => {
if (url.startsWith("data:")) {
inlineCount += 1;
return `inline-${inlineCount}`;
}
const target = nextImageInner(url) || url;
const segment = new URL(target).pathname.split("/").filter(Boolean).pop() || "image";
let decoded = segment;
try {
decoded = decodeURIComponent(segment);
} catch {
decoded = segment;
}
return decoded.replace(/\.\w{2,5}$/, "");
};
const safeName = (name) => {
return name.replace(/[\\/:*?"<>|\x00-\x1f]/g, "_").trim().slice(0, 100) || "image";
};
const PROP_KEYS = new Set(["checked", "value", "selected", "disabled", "hidden"]);
const h = (tag, props = {}, children = []) => {
const el = document.createElement(tag);
Object.entries(props).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (key === "class") {
el.className = value;
} else if (key === "text") {
el.textContent = value;
} else if (key.startsWith("on")) {
el.addEventListener(key.slice(2), value);
} else if (PROP_KEYS.has(key)) {
el[key] = value;
} else {
el.setAttribute(key, value);
}
});
children.flat().filter(Boolean).forEach((child) => el.append(child));
return el;
};
const CSS = `
:host { all: initial; }
* { box-sizing: border-box; }
[hidden] { display: none !important; }
.backdrop { position: fixed; inset: 0; background: #16171b; display: flex;
font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: #e8e8ea; }
.panel { width: 100%; height: 100%; background: #16171b; display: flex; flex-direction: column; overflow: hidden; }
.top { display: flex; align-items: center; gap: 12px; padding: 12px 16px; border-bottom: 1px solid #2c2e35; }
.title { font-weight: 650; font-size: 15px; white-space: nowrap; }
.stats { color: #9a9ca5; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 16px; border-bottom: 1px solid #2c2e35; }
.label { color: #9a9ca5; font-size: 12px; }
.field { display: inline-flex; align-items: center; gap: 6px; color: #9a9ca5; font-size: 12px; }
.divider { width: 1px; height: 22px; background: #2c2e35; margin: 0 2px; }
button { font: inherit; color: inherit; background: #24262d; border: 1px solid #34363f; border-radius: 8px; padding: 6px 11px;
cursor: pointer; white-space: nowrap; }
button:hover { background: #2d3038; }
button:disabled { opacity: .45; cursor: default; }
button.primary { background: #10a37f; border-color: #10a37f; color: #fff; font-weight: 600; padding: 8px 16px; }
button.primary:hover { background: #0e8f70; }
button.ghost { background: transparent; border-color: transparent; font-size: 18px; line-height: 1; padding: 4px 8px; }
input, select { font: inherit; color: #e8e8ea; background: #0f1013; border: 1px solid #34363f; border-radius: 8px; padding: 5px 8px; }
input:focus, select:focus, button:focus-visible { outline: 2px solid #10a37f; outline-offset: 1px; }
input[type=number] { width: 72px; }
input[type=search] { width: 170px; }
input[type=checkbox] { accent-color: #10a37f; margin: 0; padding: 0; width: 14px; height: 14px; }
.chip { display: inline-flex; align-items: center; gap: 5px; padding: 4px 9px; border: 1px solid #34363f; border-radius: 999px;
cursor: pointer; user-select: none; font-size: 12px; }
.chip.off { opacity: .45; }
.area { background: #10a37f22; border-color: #10a37f; color: #7fe0c4; }
.grid { flex: 1; min-height: 0; overflow-x: hidden; overflow-y: scroll; padding: 14px 16px; display: grid;
grid-template-columns: repeat(auto-fill, minmax(var(--col, 220px), 1fr)); grid-auto-rows: max-content; gap: 12px;
align-content: start; align-items: start; }
.grid::-webkit-scrollbar { width: 14px; }
.grid::-webkit-scrollbar-track { background: #101114; }
.grid::-webkit-scrollbar-thumb { background: #454955; border-radius: 10px; border: 3px solid #101114; min-height: 40px; }
.grid::-webkit-scrollbar-thumb:hover { background: #5d6270; }
@supports (-moz-appearance: none) { .grid { scrollbar-color: #454955 #101114; } }
.card { position: relative; border: 2px solid #24262d; border-radius: 10px; background: #0f1013; overflow: hidden; cursor: pointer; }
.card:hover { border-color: #3a3d47; }
.card.on { border-color: #10a37f; }
.thumb { min-height: 90px; background: repeating-conic-gradient(#1c1e23 0 25%, #141519 0 50%) 0 0 / 16px 16px; }
.thumb { position: relative; }
.thumb img, .thumb video { width: 100%; height: auto; display: block; }
.play { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 40px; height: 40px; border-radius: 50%;
background: rgba(0,0,0,.6); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 15px;
pointer-events: none; }
.card:hover .play { opacity: 0; }
.kind { font-size: 10px; font-weight: 700; padding: 1px 5px; border-radius: 4px; margin-left: 4px; }
.kind.gif { background: #a855f733; color: #d8b4fe; }
.kind.video { background: #3b82f633; color: #93c5fd; }
.chip.kind-chip { font-weight: 600; padding: 5px 11px; }
.meta { display: flex; justify-content: space-between; align-items: center; gap: 6px; padding: 5px 7px; font-size: 11px; color: #9a9ca5; }
.type { font-weight: 600; color: #c9cbd2; }
.badge { font-size: 10px; font-weight: 700; padding: 1px 5px; border-radius: 4px; background: #10a37f33; color: #7fe0c4; margin-left: 4px; }
.full { color: #7fe0c4; font-weight: 600; }
.sentinel { grid-column: 1 / -1; text-align: center; color: #9a9ca5; padding: 18px; font-size: 12px; }
.tick { position: absolute; top: 7px; left: 7px; width: 22px; height: 22px; border-radius: 50%; background: rgba(0,0,0,.55);
border: 2px solid rgba(255,255,255,.85); color: transparent; display: flex; align-items: center; justify-content: center;
font-size: 13px; font-weight: 700; }
.card.on .tick { background: #10a37f; border-color: #10a37f; color: #fff; }
.actions { position: absolute; top: 6px; right: 6px; display: flex; gap: 4px; }
.actions button { padding: 3px 8px; font-size: 13px; background: rgba(0,0,0,.65); border-color: transparent; color: #fff; }
.actions button:hover { background: #10a37f; }
.actions .open { opacity: 0; }
.card:hover .actions .open { opacity: 1; }
.empty { grid-column: 1 / -1; text-align: center; color: #9a9ca5; padding: 60px 20px; }
.foot { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px 16px; border-top: 1px solid #2c2e35; }
.spacer { flex: 1; }
.progress { height: 3px; background: #24262d; }
.progress > div { height: 100%; width: 0; background: #10a37f; transition: width .2s; }
.status { padding: 6px 16px 10px; color: #9a9ca5; font-size: 12px; min-height: 28px; }
.highlight { position: fixed; pointer-events: none; border: 2px solid #10a37f; background: rgba(16,163,127,.14); border-radius: 6px;
display: none; }
.hint { position: fixed; top: 14px; left: 50%; transform: translateX(-50%); background: #16171b; color: #e8e8ea; border: 1px solid #10a37f;
border-radius: 10px; padding: 8px 14px; font: 13px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; display: none;
box-shadow: 0 10px 30px rgba(0,0,0,.4); pointer-events: none; }
`;
const applyStyles = (root) => {
try {
const sheet = new CSSStyleSheet();
sheet.replaceSync(CSS);
root.adoptedStyleSheets = [sheet];
} catch {
root.append(h("style", { text: CSS }));
}
};
const state = {
minSize: OPTIONS.minSize,
kinds: new Set(OPTIONS.defaultKinds),
types: new Set(TYPES),
query: "",
sort: "page",
area: null,
mode: "zip",
naming: "original",
prefix: SITE,
format: "original",
quality: OPTIONS.defaultQuality,
busy: false,
loading: false,
};
let visible = [];
let lastClicked = -1;
let renderTimer = 0;
let resetPending = false;
let shownCount = OPTIONS.batchSize;
const host = h("div", { id: HOST_ID });
Object.assign(host.style, { position: "fixed", top: "0", left: "0", right: "0", bottom: "0", zIndex: "2147483647" });
const root = host.attachShadow({ mode: "open" });
applyStyles(root);
const statsEl = h("div", { class: "stats" });
const statusEl = h("div", { class: "status" });
const progressFill = h("div");
const grid = h("div", { class: "grid" });
const emptyEl = h("div", { class: "empty", text: "Nothing matches these filters. Turn on Images, GIFs or Videos above, turn format chips back on or lower the min size." });
const highlightEl = h("div", { class: "highlight" });
const hintEl = h("div", { class: "hint" });
const sentinel = h("div", { class: "sentinel" });
const setStatus = (text) => {
statusEl.textContent = text;
};
const setProgress = (fraction) => {
progressFill.style.width = `${Math.round(fraction * 100)}%`;
};
const scheduleRender = (reset = false) => {
resetPending = resetPending || reset;
clearTimeout(renderTimer);
renderTimer = setTimeout(() => render(resetPending), 150);
};
const containsDeep = (ancestor, node) => {
let current = node;
while (current) {
if (current === ancestor) {
return true;
}
current = current.parentNode || current.host;
}
return false;
};
const passesFilters = (item) => {
if (item.broken || !state.kinds.has(item.kind) || !state.types.has(item.type)) {
return false;
}
if (item.w && item.h && (item.w < state.minSize || item.h < state.minSize)) {
return false;
}
if (state.query && !`${item.url} ${item.alt}`.toLowerCase().includes(state.query)) {
return false;
}
if (state.area && ![...item.els].some((el) => containsDeep(state.area, el))) {
return false;
}
return true;
};
const SORTERS = {
page: (a, b) => a.order - b.order,
big: (a, b) => b.w * b.h - a.w * a.h || a.order - b.order,
small: (a, b) => a.w * a.h - b.w * b.h || a.order - b.order,
};
const onCardClick = (item, event) => {
const index = visible.indexOf(item);
const turnOn = !selected.has(item);
const range = event.shiftKey && lastClicked >= 0 ? visible.slice(Math.min(lastClicked, index), Math.max(lastClicked, index) + 1) : [item];
range.forEach((it) => {
if (turnOn) {
selected.add(it);
} else {
selected.delete(it);
}
});
lastClicked = index;
refreshSelection();
};
const formatDuration = (seconds) => {
if (!Number.isFinite(seconds) || seconds <= 0) {
return "";
}
const total = Math.round(seconds);
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
};
const sizeLabel = (item) => {
const size = item.w ? `${item.w}×${item.h}` : "SVG";
const duration = formatDuration(item.duration);
return duration ? `${size} · ${duration}` : size;
};
const videoPreview = (item) => {
const video = h("video", { muted: true, loop: true, playsinline: "", preload: "metadata" });
video.muted = true;
if (item.poster) {
video.poster = item.poster;
}
video.src = item.url;
video.addEventListener("loadedmetadata", () => {
if (!item.poster && video.duration > 0.2) {
video.currentTime = 0.1;
}
if (!item.probed || !item.w) {
setSize(item, video.videoWidth, video.videoHeight, video.duration);
}
});
return video;
};
const playOnHover = (card, video) => {
card.addEventListener("mouseenter", () => video.play().catch(() => null));
card.addEventListener("mouseleave", () => video.pause());
};
const cardFor = (item) => {
if (item.card) {
return item.card;
}
const isVideo = item.kind === "video";
const media = isVideo ? videoPreview(item) : h("img", { alt: item.alt || "", loading: "lazy", decoding: "async" });
if (item.w && item.h) {
media.style.aspectRatio = `${item.w} / ${item.h}`;
}
if (!isVideo) {
media.src = item.preview;
}
item.thumbImg = media;
item.dimsEl = h("span", { text: item.w ? sizeLabel(item) : "…" });
const hasBigger = item.hd.length > 0 || item.url !== item.preview;
const typeLabel = h("span", { class: "type", text: item.type.toUpperCase() }, [
item.kind !== "image" ? h("span", { class: `kind ${item.kind}`, text: item.kind === "gif" ? "GIF" : "VIDEO" }) : null,
hasBigger ? h("span", { class: "badge", title: "A larger version may be available", text: "HD" }) : null,
]);
const actionButton = (className, title, text, handler) => {
return h("button", {
class: className,
title,
text,
onclick: (event) => {
event.stopPropagation();
handler();
},
});
};
item.card = h("div", { class: "card", title: item.alt ? `${item.alt}\n${item.url}` : item.url }, [
h("div", { class: "thumb" }, [media, isVideo ? h("div", { class: "play", text: "▶" }) : null]),
h("div", { class: "tick", text: "✓" }),
h("div", { class: "actions" }, [
actionButton("open", "Open in a new tab", "↗", () => window.open(item.url, "_blank", "noopener")),
actionButton("save", "Download just this one", "⬇", () => downloadOne(item)),
]),
h("div", { class: "meta" }, [typeLabel, item.dimsEl]),
]);
if (isVideo) {
playOnHover(item.card, media);
}
item.card.addEventListener("click", (event) => onCardClick(item, event));
return item.card;
};
const chosenItems = () => {
return visible.filter((item) => selected.has(item));
};
const downloadButton = h("button", { class: "primary" });
const updateStats = () => {
const all = [...items.values()];
const broken = all.filter((item) => item.broken).length;
const pending = all.filter((item) => !item.probed).length;
const parts = [`${all.length} found`, `${visible.length} shown`, `${chosenItems().length} selected`];
if (pending) {
parts.push(`checking size of ${pending}`);
}
if (broken) {
parts.push(`${broken} failed to load`);
}
statsEl.textContent = parts.join(" · ");
const count = chosenItems().length;
downloadButton.textContent = state.mode === "zip" ? `Download ZIP (${count})` : `Download files (${count})`;
downloadButton.disabled = state.busy || !count;
};
const refreshSelection = () => {
visible.forEach((item) => item.card?.classList.toggle("on", selected.has(item)));
updateStats();
};
const typeChips = new Map();
const kindChips = new Map();
const updateTypeChips = () => {
const counts = new Map(TYPES.map((type) => [type, 0]));
const kindCounts = new Map(KINDS.map(([kind]) => [kind, 0]));
items.forEach((item) => {
if (item.broken) {
return;
}
kindCounts.set(item.kind, kindCounts.get(item.kind) + 1);
if (state.kinds.has(item.kind)) {
counts.set(item.type, counts.get(item.type) + 1);
}
});
typeChips.forEach((chip, type) => {
chip.count.textContent = `${type.toUpperCase()} ${counts.get(type)}`;
chip.el.hidden = counts.get(type) === 0;
chip.el.classList.toggle("off", !state.types.has(type));
});
kindChips.forEach((chip, kind) => {
chip.count.textContent = `${chip.label} ${kindCounts.get(kind)}`;
chip.el.classList.toggle("off", !state.kinds.has(kind));
});
};
const updateSentinel = () => {
const shown = Math.min(shownCount, visible.length);
sentinel.hidden = shown >= visible.length;
sentinel.textContent = `Showing ${shown} of ${visible.length} · scroll down to see more`;
};
const nearBottom = () => {
return grid.scrollTop + grid.clientHeight >= grid.scrollHeight - 700;
};
const showMore = () => {
const next = visible.slice(shownCount, shownCount + OPTIONS.batchSize);
shownCount += next.length;
sentinel.before(...next.map(cardFor));
refreshSelection();
updateSentinel();
};
const watchSentinel = () => {
if (grid.isConnected && grid.clientHeight && shownCount < visible.length && nearBottom()) {
showMore();
setTimeout(watchSentinel, 50);
}
};
grid.addEventListener("scroll", watchSentinel, { passive: true });
const render = (reset = false) => {
clearTimeout(renderTimer);
resetPending = false;
visible = [...items.values()].filter(passesFilters).sort(SORTERS[state.sort]);
lastClicked = -1;
if (reset) {
shownCount = OPTIONS.batchSize;
grid.scrollTop = 0;
}
const shown = visible.slice(0, shownCount);
grid.replaceChildren(...(visible.length ? shown.map(cardFor) : [emptyEl]), sentinel);
updateSentinel();
updateTypeChips();
refreshSelection();
watchSentinel();
};
let probeRunning = false;
const probeVideo = (item) => {
return new Promise((resolve) => {
const video = document.createElement("video");
let finished = false;
const finish = () => {
if (finished) {
return;
}
finished = true;
setSize(item, video.videoWidth, video.videoHeight, video.duration);
video.removeAttribute("src");
video.load();
resolve();
};
video.preload = "metadata";
video.muted = true;
video.onloadedmetadata = finish;
video.onerror = finish;
setTimeout(finish, OPTIONS.probeTimeoutMs);
video.src = item.url;
});
};
const probeOne = (item) => {
if (item.kind === "video") {
return probeVideo(item);
}
return new Promise((resolve) => {
const img = new Image();
let finished = false;
const finish = (ok) => {
if (finished) {
return;
}
finished = true;
if (ok) {
setSize(item, img.naturalWidth, img.naturalHeight);
} else {
item.probed = true;
item.broken = true;
}
resolve();
};
img.onload = () => finish(true);
img.onerror = () => finish(false);
setTimeout(() => finish(true), OPTIONS.probeTimeoutMs);
img.src = item.preview;
});
};
const setSize = (item, width, height, duration = 0) => {
item.probed = true;
item.w = width || 0;
item.h = height || 0;
item.duration = Number.isFinite(duration) ? duration : 0;
if (item.dimsEl && !item.fullSize) {
item.dimsEl.textContent = item.w || item.kind !== "video" ? sizeLabel(item) : "VIDEO";
}
if (item.thumbImg && width && height) {
item.thumbImg.style.aspectRatio = `${width} / ${height}`;
}
};
const sizeFromPage = (item) => {
const shown = [...item.els].find((el) => {
if (el.tagName === "VIDEO") {
return item.kind === "video" && el.readyState >= 1 && el.videoWidth && el.currentSrc === item.url;
}
return el.tagName === "IMG" && el.complete && el.naturalWidth && el.currentSrc === item.preview;
});
if (shown?.tagName === "VIDEO") {
setSize(item, shown.videoWidth, shown.videoHeight, shown.duration);
} else if (shown) {
setSize(item, shown.naturalWidth, shown.naturalHeight);
}
};
const probeSizes = async () => {
if (probeRunning) {
return;
}
probeRunning = true;
for (;;) {
items.forEach((item) => {
if (!item.probed) {
sizeFromPage(item);
}
});
const queue = [...items.values()].filter((item) => !item.probed && !item.probing);
if (!queue.length) {
break;
}
queue.forEach((item) => {
item.probing = true;
});
const worker = async () => {
while (queue.length) {
await probeOne(queue.shift());
scheduleRender();
}
};
await Promise.all(Array.from({ length: OPTIONS.probeConcurrency }, worker));
}
probeRunning = false;
render();
};
const snapshot = () => {
return `${items.size}|${document.documentElement.scrollHeight}|${document.images.length}`;
};
const loadMoreButton = h("button", { text: "Load more from page" });
const loadMore = async () => {
if (state.loading) {
state.loading = false;
return;
}
state.loading = true;
loadMoreButton.textContent = "Stop loading";
let idleRounds = 0;
for (let round = 1; round <= OPTIONS.maxLoadRounds && state.loading; round++) {
const before = snapshot();
const button = findLoadMoreButton();
if (button) {
button.scrollIntoView({ block: "center" });
button.click();
}
scrollEverythingDown();
await sleep(OPTIONS.waitAfterLoadMs);
scanPage();
probeSizes();
scheduleRender();
setStatus(`Load round ${round}: ${items.size} images so far${button ? " (clicked the page's Load more button)" : ""}`);
idleRounds = snapshot() === before ? idleRounds + 1 : 0;
if (idleRounds >= OPTIONS.idleRoundsToStop) {
setStatus(`No more images are loading on the page. ${items.size} images in total.`);
break;
}
}
state.loading = false;
loadMoreButton.textContent = "Load more from page";
render();
};
const areaChip = h("span", { class: "chip area", hidden: true, title: "Remove area filter" });
const updateAreaChip = () => {
areaChip.hidden = !state.area;
if (state.area) {
const tag = state.area.tagName.toLowerCase();
const cls = typeof state.area.className === "string" ? state.area.className.trim().split(/\s+/)[0] : "";
areaChip.textContent = `Only this area: <${tag}${cls ? `.${cls}` : ""}> ✕`;
}
};
const countAreaImages = (el) => {
return el.querySelectorAll(AREA_IMAGE_SELECTOR).length + (el.matches(AREA_IMAGE_SELECTOR) ? 1 : 0);
};
const containerFor = (el, extraLevels) => {
let current = el;
while (current.parentElement && current !== document.body && countAreaImages(current) < OPTIONS.minImagesForArea) {
current = current.parentElement;
}
for (let i = 0; i < extraLevels && current.parentElement && current !== document.body; i++) {
current = current.parentElement;
}
return current;
};
const picker = { target: null, levels: 0, chosen: null };
const showHighlight = () => {
if (!picker.chosen) {
return;
}
const rect = picker.chosen.getBoundingClientRect();
Object.assign(highlightEl.style, {
display: "block",
top: `${rect.top}px`,
left: `${rect.left}px`,
width: `${rect.width}px`,
height: `${rect.height}px`,
});
hintEl.textContent = `${countAreaImages(picker.chosen)} images in this area · Click to choose · ↑ larger area · ↓ smaller · Esc to cancel`;
};
const updatePick = () => {
if (picker.target) {
picker.chosen = containerFor(picker.target, picker.levels);
showHighlight();
}
};
const blockEvent = (event) => {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
};
const onPickMove = (event) => {
const target = document.elementFromPoint(event.clientX, event.clientY);
if (target && target !== picker.target) {
picker.target = target;
picker.levels = 0;
updatePick();
}
};
const onPickClick = (event) => {
blockEvent(event);
finishPick(picker.chosen);
};
const onPickKey = (event) => {
if (event.key === "Escape") {
blockEvent(event);
finishPick(null);
} else if (event.key === "ArrowUp") {
blockEvent(event);
picker.levels += 1;
updatePick();
} else if (event.key === "ArrowDown") {
blockEvent(event);
picker.levels = Math.max(0, picker.levels - 1);
updatePick();
}
};
const PICK_EVENTS = [
["mousemove", onPickMove],
["click", onPickClick],
["mousedown", blockEvent],
["mouseup", blockEvent],
["pointerdown", blockEvent],
["pointerup", blockEvent],
["keydown", onPickKey],
["scroll", showHighlight],
];
const backdrop = h("div", { class: "backdrop" });
const stopPicking = () => {
PICK_EVENTS.forEach(([type, handler]) => window.removeEventListener(type, handler, true));
host.style.pointerEvents = "";
backdrop.style.display = "";
highlightEl.style.display = "none";
hintEl.style.display = "none";
};
const finishPick = (el) => {
stopPicking();
if (el) {
state.area = el;
scanPage();
probeSizes();
selected.clear();
items.forEach((item) => {
if ([...item.els].some((node) => containsDeep(el, node))) {
selected.add(item);
}
});
}
updateAreaChip();
render(true);
};
const startPick = () => {
Object.assign(picker, { target: null, levels: 0, chosen: null });
host.style.pointerEvents = "none";
backdrop.style.display = "none";
hintEl.style.display = "block";
hintEl.textContent = "Hover over the box or grid with the images and click it · Esc to cancel";
PICK_EVENTS.forEach(([type, handler]) => window.addEventListener(type, handler, true));
};
areaChip.addEventListener("click", () => {
state.area = null;
updateAreaChip();
render(true);
});
const fileListFor = (chosen) => {
return chosen.map((item) => item.url).join("\n");
};
const copyUrls = async () => {
const text = fileListFor(chosenItems());
try {
await navigator.clipboard.writeText(text);
} catch {
const area = h("textarea", { value: text });
root.append(area);
area.select();
document.execCommand("copy");
area.remove();
}
setStatus(`Copied ${chosenItems().length} URLs.`);
};
const saveUrlList = () => {
saveBlob(new Blob([fileListFor(chosenItems())], { type: "text/plain" }), `${safeName(state.prefix || SITE)}-media-urls.txt`);
setStatus(`Saved ${chosenItems().length} URLs as a .txt file.`);
};
const busyControls = [];
const setBusy = (busy) => {
state.busy = busy;
busyControls.forEach((control) => {
control.disabled = busy;
});
updateStats();
};
const showFullSize = (item, file) => {
if (!item.dimsEl) {
return;
}
const isVideo = VIDEO_TYPES.has(file.kind);
if (!isVideo && (!file.w || !file.h)) {
return;
}
item.fullSize = true;
item.dimsEl.textContent = isVideo ? `${item.w ? sizeLabel(item) : "VIDEO"} ✓` : `${file.w}×${file.h} ✓`;
item.dimsEl.className = "full";
item.dimsEl.title = "Downloaded at this size";
};
const keepsOriginal = (kind) => {
return kind === "gif" || kind === "svg" || VIDEO_TYPES.has(kind);
};
const prepareFile = async (item, notes) => {
const file = await fetchBest(item, state.quality);
if (file.url !== item.url) {
notes.hd += 1;
}
showFullSize(item, file);
if (state.format === "original" || state.format === file.kind) {
return file;
}
if (keepsOriginal(file.kind)) {
notes.keptOriginal += 1;
return file;
}
try {
return await convertImage(file, state.format);
} catch {
notes.convertFailed += 1;
return file;
}
};
const newNotes = () => {
return { hd: 0, convertFailed: 0, keptOriginal: 0 };
};
const downloadOne = async (item) => {
if (item.downloading) {
return;
}
item.downloading = true;
setStatus(`Downloading ${safeName(baseNameFor(item.url))}...`);
try {
const notes = newNotes();
const file = await prepareFile(item, notes);
const position = visible.indexOf(item) + 1 || item.order;
const prefix = safeName(state.prefix || SITE);
const base = state.naming === "numbered" ? `${prefix}-${String(position).padStart(3, "0")}` : safeName(baseNameFor(file.url));
const name = `${base}.${file.kind}`;
saveBlob(new Blob([file.bytes], { type: MIME[file.kind] || "application/octet-stream" }), name);
const megabytes = (file.bytes.length / 1024 / 1024).toFixed(2);
setStatus(`Saved ${name} (${megabytes} MB)${notes.hd ? ", found at a larger size than the page shows" : ""}.`);
} catch (err) {
setStatus(`Could not download this one: ${err.message || err}`);
log("Single download failed:", item.url, err);
}
item.downloading = false;
};
const startDownload = async () => {
const chosen = chosenItems();
if (!chosen.length || state.busy) {
return;
}
setBusy(true);
setProgress(0);
const results = new Array(chosen.length);
const failed = [];
const notes = newNotes();
const queue = chosen.map((item, index) => ({ item, index }));
let done = 0;
const worker = async () => {
while (queue.length) {
const { item, index } = queue.shift();
try {
results[index] = await prepareFile(item, notes);
} catch (err) {
failed.push({ url: item.url, reason: err.message || String(err) });
}
done += 1;
setProgress(done / chosen.length);
setStatus(`Downloaded ${done} of ${chosen.length} files...`);
}
};
await Promise.all(Array.from({ length: OPTIONS.concurrency }, worker));
const ok = results.filter(Boolean);
const digits = Math.max(3, String(ok.length).length);
const usedNames = new Map();
const prefix = safeName(state.prefix || SITE);
inlineCount = 0;
const files = ok.map((file, index) => {
const base = state.naming === "numbered" ? `${prefix}-${String(index + 1).padStart(digits, "0")}` : safeName(baseNameFor(file.url));
const key = `${base}.${file.kind}`.toLowerCase();
const seen = usedNames.get(key) || 0;
usedNames.set(key, seen + 1);
return { name: seen ? `${base}-${seen}.${file.kind}` : `${base}.${file.kind}`, data: file.bytes, kind: file.kind };
});
if (failed.length) {
log(`${failed.length} file(s) could not be downloaded:`);
console.table(failed);
}
if (!files.length) {
setStatus(`Nothing could be downloaded (${failed.length} failed). The reasons are in a table in the console.`);
setBusy(false);
return;
}
const totalBytes = files.reduce((sum, file) => sum + file.data.length, 0);
const megabytes = (totalBytes / 1024 / 1024).toFixed(2);
if (state.mode === "zip") {
if (totalBytes > 0xfffffff0 || files.length > 0xffff) {
setStatus("That is over 4 GB or 65,535 files. Select fewer files and download in parts.");
setBusy(false);
return;
}
saveBlob(new Blob(buildZip(files), { type: "application/zip" }), `${prefix}-media.zip`);
} else {
setStatus("Saving files one by one. If the browser asks, choose Allow multiple downloads.");
for (const file of files) {
saveBlob(new Blob([file.data], { type: MIME[file.kind] || "application/octet-stream" }), file.name);
await sleep(350);
}
}
const extras = [];
if (notes.hd) {
extras.push(`${notes.hd} found at a larger (original) size than the page shows`);
}
if (notes.keptOriginal) {
extras.push(`${notes.keptOriginal} GIFs, SVGs or videos kept their original format`);
}
if (notes.convertFailed) {
extras.push(`${notes.convertFailed} could not be converted and kept their original format`);
}
if (failed.length) {
extras.push(`${failed.length} failed (listed in the console)`);
}
setStatus(`Done: ${files.length} files, ${megabytes} MB${extras.length ? ` · ${extras.join(" · ")}` : ""}`);
log(`Done: ${files.length} files, ${megabytes} MB`);
setBusy(false);
};
const selectVisible = (mode) => {
visible.forEach((item) => {
const on = mode === "all" || (mode === "invert" && !selected.has(item));
if (on) {
selected.add(item);
} else {
selected.delete(item);
}
});
refreshSelection();
};
const firstNInput = h("input", { type: "number", min: "1", value: "20" });
const selectFirstN = () => {
const count = Number.parseInt(firstNInput.value, 10);
if (!Number.isFinite(count) || count < 1) {
setStatus("How many? Enter a valid number.");
return;
}
selected.clear();
visible.slice(0, count).forEach((item) => selected.add(item));
refreshSelection();
setStatus(`Selected the first ${Math.min(count, visible.length)} items.`);
};
const selectBox = (options, value, onChange) => {
return h(
"select",
{ onchange: (event) => onChange(event.target.value) },
options.map(([optionValue, label]) => h("option", { value: optionValue, text: label, selected: optionValue === value })),
);
};
const close = () => {
state.loading = false;
stopPicking();
host.remove();
delete window.__znImageGrabberCleanup;
};
window.__znImageGrabberCleanup = close;
KINDS.forEach(([kind, label]) => {
const count = h("span");
const el = h("span", { class: "chip kind-chip", title: `Show or hide ${label.toLowerCase()}` }, [count]);
el.addEventListener("click", () => {
if (state.kinds.has(kind)) {
state.kinds.delete(kind);
} else {
state.kinds.add(kind);
}
render(true);
});
kindChips.set(kind, { el, count, label });
});
TYPES.forEach((type) => {
const count = h("span");
const el = h("span", { class: "chip", title: "Click to turn on or off" }, [count]);
el.addEventListener("click", () => {
if (state.types.has(type)) {
state.types.delete(type);
} else {
state.types.add(type);
}
render(true);
});
typeChips.set(type, { el, count });
});
const prefixInput = h("input", {
type: "text",
value: state.prefix,
title: "Start of numbered file names, also used for the ZIP name",
oninput: (event) => {
state.prefix = event.target.value.trim();
},
});
prefixInput.style.width = "140px";
const THUMB_SIZES = { small: "150px", medium: "220px", large: "320px" };
const copyButton = h("button", { text: "URLs copy", onclick: copyUrls });
const txtButton = h("button", { text: "URLs .txt", onclick: saveUrlList });
const areaButton = h("button", { text: "Pick area", title: "Only take images from one box or grid on the page", onclick: startPick });
downloadButton.addEventListener("click", startDownload);
loadMoreButton.addEventListener("click", loadMore);
busyControls.push(copyButton, txtButton, areaButton);
const panel = h("div", { class: "panel", role: "dialog", "aria-label": "Media ZIP Grabber" }, [
h("div", { class: "top" }, [
h("div", { class: "title", text: "Media ZIP Grabber" }),
statsEl,
h("button", { class: "ghost", title: "Close (Esc)", text: "✕", onclick: close }),
]),
h("div", { class: "bar" }, [
h("span", { class: "label", text: "Show" }),
[...kindChips.values()].map((chip) => chip.el),
h("div", { class: "divider" }),
h("span", { class: "label", text: "Formats" }),
[...typeChips.values()].map((chip) => chip.el),
]),
h("div", { class: "bar" }, [
h("label", { class: "field" }, [
"Min size",
h("input", {
type: "number",
min: "0",
value: String(state.minSize),
oninput: (event) => {
state.minSize = Number.parseInt(event.target.value, 10) || 0;
scheduleRender(true);
},
}),
"px",
]),
h("div", { class: "divider" }),
h("input", {
type: "search",
placeholder: "Search URL or name",
oninput: (event) => {
state.query = event.target.value.trim().toLowerCase();
scheduleRender(true);
},
}),
selectBox(
[
["page", "Page order"],
["big", "Largest first"],
["small", "Smallest first"],
],
state.sort,
(value) => {
state.sort = value;
render(true);
},
),
h("label", { class: "field" }, [
"Thumbnail",
selectBox(
[
["small", "Small"],
["medium", "Medium"],
["large", "Large"],
],
"medium",
(value) => {
grid.style.setProperty("--col", THUMB_SIZES[value]);
},
),
]),
]),
h("div", { class: "bar" }, [
h("button", { text: "Select all", onclick: () => selectVisible("all") }),
h("button", { text: "Select none", onclick: () => selectVisible("none") }),
h("button", { text: "Invert", onclick: () => selectVisible("invert") }),
h("div", { class: "divider" }),
h("label", { class: "field" }, ["First", firstNInput]),
h("button", { text: "Select", onclick: selectFirstN }),
h("div", { class: "divider" }),
areaButton,
areaChip,
loadMoreButton,
h("span", { class: "label", text: "Shift + click = range select" }),
]),
grid,
h("div", { class: "progress" }, [progressFill]),
h("div", { class: "foot" }, [
h("label", { class: "field" }, [
"Save as",
selectBox(
[
["zip", "One ZIP file"],
["files", "Separate files"],
],
state.mode,
(value) => {
state.mode = value;
updateStats();
},
),
]),
h("label", { class: "field" }, [
"Names",
selectBox(
[
["original", "Original names"],
["numbered", "Numbered (prefix-001)"],
],
state.naming,
(value) => {
state.naming = value;
},
),
]),
h("label", { class: "field" }, ["Prefix", prefixInput]),
h("label", { class: "field" }, [
"Format",
selectBox(
[
["original", "Original format"],
["jpg", "JPG"],
["png", "PNG"],
["webp", "WebP"],
],
state.format,
(value) => {
state.format = value;
},
),
]),
h("label", { class: "field", title: "Full resolution checks every larger version it can find and downloads the biggest (original) one" }, [
"Quality",
selectBox(
[
["full", "Full resolution (largest)"],
["page", "As shown on page"],
],
state.quality,
(value) => {
state.quality = value;
},
),
]),
h("div", { class: "spacer" }),
copyButton,
txtButton,
downloadButton,
]),
statusEl,
]);
backdrop.append(panel);
["keydown", "keyup", "keypress"].forEach((type) => {
backdrop.addEventListener(type, (event) => {
event.stopPropagation();
if (type === "keydown" && event.key === "Escape") {
close();
}
});
});
root.append(backdrop, highlightEl, hintEl);
(document.body || document.documentElement).append(host);
scanPage();
render();
setStatus(
`Choose Images, GIFs or Videos at the top. Click cards to select them, use ⬇ on a card to save just that one, or pick options below and press Download. Full resolution finds the largest version of each image.${
streamingVideos.size ? ` ${streamingVideos.size} streaming video(s) on this page use blob: URLs and cannot be downloaded.` : ""
}`,
);
log(`Found ${items.size} images, GIFs and videos. Panel is open.`);
probeSizes();
if (OPTIONS.autoLoadOnStart) {
loadMore();
}
})();A console snippet for media-heavy pages such as galleries, shops, portfolios, GIF sites and video grids. It finds every image, GIF and video on the page (img, srcset and picture, lazy data-src, CSS backgrounds, video and source tags, links to media files, og:video, shadow DOM and anything already loaded over the network) and opens a full-screen panel. At the top you choose what to show (Images, GIFs, Videos) and which formats (JPG, PNG, WebP, GIF, SVG, AVIF, MP4, WebM, MOV). Thumbnails appear 60 at a time as you scroll; videos show their first frame, size and length and play on hover. Filter by minimum size or a word in the URL, sort by size, limit to one box or grid you click on the page, and keep clicking Load more from the panel. Every card has its own download button, or select cards (shift-click for a range, or the first N) and save them as one ZIP or separate files with original or numbered names. Full resolution checks every larger version of an image it can find (linked originals, srcset, size parameters such as ?w=400 and many CDN patterns), reads each file's real pixel size and keeps the biggest. Still images can be converted to JPG, PNG or WebP; GIFs and videos always keep their original format. Streaming videos that use blob: URLs cannot be downloaded and are counted in the panel. Everything runs in the browser with no library; files another site blocks with CORS are listed in the console.
Grab images, GIFs and videos from any page in a full-screen grid. Save one at a time or all as a ZIP.