Skip to content
ZNZN Hub

$ run gif-zip-downloader

working on it…

✓ all done

  • Auto clicks Load more and scrolls feeds
  • Checks real GIF bytes, not just the URL
  • Builds the ZIP in the browser, no library
  • Asks how many GIFs you want
Install

Up and running in a minute

  1. 01

    Open the page that has the GIFs.

  2. 02

    Open the console: F12 or Ctrl+Shift+J on Windows, Cmd+Option+J on Mac. Chrome may ask you to type allow pasting first.

  3. 03

    Copy the script below, paste it into the console and press Enter. Type a number or all, and the ZIP downloads when it is done.

Source

Read it, copy it, run it

The full script is below. Copy it in one click or download the file. Nothing is minified or hidden.

gif-zip-downloader.jsJavaScript · 456 linesDownload
(async () => {
  const OPTIONS = {
    maxGifs: 100,
    askForCount: true,
    autoLoadMore: true,
    maxLoadRounds: 60,
    idleRoundsToStop: 3,
    waitAfterLoadMs: 1500,
    sniffAllImages: false,
    concurrency: 4,
    zipName: `${location.hostname || "page"}-gifs.zip`,
  };

  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 LAZY_ATTRS = ["src", "data-src", "data-original", "data-lazy-src", "data-gif", "data-url", "poster"];
  const MEDIA_TAGS = new Set(["img", "source", "video", "input"]);
  const LINK_TAGS = new Set(["a", "link"]);

  const log = (...args) => {
    console.log("%c[GIF-ZIP]", "color:#0a7;font-weight:bold", ...args);
  };

  const gifUrls = new Set();
  const otherImageUrls = new Set();

  const looksLikeGif = (url) => {
    return (
      /^data:image\/gif/i.test(url) ||
      /\.gif(?:$|[?#])/i.test(url) ||
      /[?&](?:format|fm|ext|type)=gif\b/i.test(url)
    );
  };

  const toAbsoluteUrl = (value) => {
    if (value.startsWith("data:")) {
      return value;
    }
    try {
      return new URL(value, location.href).href;
    } catch {
      return null;
    }
  };

  const addUrl = (raw) => {
    if (!raw || typeof raw !== "string") {
      return;
    }
    const value = raw.trim();
    if (!value || value.startsWith("blob:")) {
      return;
    }
    const absolute = toAbsoluteUrl(value);
    if (!absolute) {
      return;
    }
    if (looksLikeGif(absolute)) {
      gifUrls.add(absolute);
    } else {
      otherImageUrls.add(absolute);
    }
  };

  const addSrcset = (srcset) => {
    if (!srcset) {
      return;
    }
    srcset.split(/,\s+(?=\S)/).forEach((part) => {
      addUrl(part.trim().split(/\s+/)[0]);
    });
  };

  const addCssUrls = (cssValue) => {
    if (!cssValue || cssValue === "none") {
      return;
    }
    for (const match of cssValue.matchAll(/url\(\s*(['"]?)(.*?)\1\s*\)/g)) {
      addUrl(match[2]);
    }
  };

  const collectElements = (root, bucket) => {
    root.querySelectorAll("*").forEach((el) => {
      bucket.push(el);
      if (el.shadowRoot) {
        collectElements(el.shadowRoot, bucket);
      }
    });
    return bucket;
  };

  const scanMediaElement = (el) => {
    if (el.currentSrc) {
      addUrl(el.currentSrc);
    }
    LAZY_ATTRS.forEach((attr) => {
      addUrl(el.getAttribute(attr));
    });
    addSrcset(el.getAttribute("srcset"));
    addSrcset(el.getAttribute("data-srcset"));
  };

  const scanLinkElement = (el) => {
    const href = el.getAttribute("href");
    if (href && looksLikeGif(href)) {
      addUrl(href);
    }
  };

  const scanStyles = (el) => {
    addCssUrls(el.getAttribute("style"));
    const computed = getComputedStyle(el);
    addCssUrls(computed.backgroundImage);
    addCssUrls(computed.borderImageSource);
    addCssUrls(computed.listStyleImage);
    ["::before", "::after"].forEach((pseudo) => {
      const pseudoStyle = getComputedStyle(el, pseudo);
      addCssUrls(pseudoStyle.backgroundImage);
      addCssUrls(pseudoStyle.content);
    });
  };

  const scanElement = (el) => {
    const tag = el.tagName.toLowerCase();
    if (MEDIA_TAGS.has(tag)) {
      scanMediaElement(el);
    } else if (LINK_TAGS.has(tag)) {
      scanLinkElement(el);
    } else if (tag === "image") {
      addUrl(el.getAttribute("href") || el.getAttribute("xlink:href"));
    }
    scanStyles(el);
  };

  const scanNetworkEntries = () => {
    performance.getEntriesByType("resource").forEach((entry) => {
      const isImageLoad = entry.initiatorType === "img" || entry.initiatorType === "css";
      if (isImageLoad || looksLikeGif(entry.name)) {
        addUrl(entry.name);
      }
    });
  };

  const scanPage = () => {
    collectElements(document, []).forEach(scanElement);
    scanNetworkEntries();
  };

  const sleep = (ms) => {
    return new Promise((resolve) => setTimeout(resolve, ms));
  };

  const isVisible = (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) && isVisible(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 pageSnapshot = () => {
    return `${gifUrls.size}|${document.documentElement.scrollHeight}|${document.images.length}`;
  };

  const autoLoad = async () => {
    const enough = OPTIONS.maxGifs + 10;
    let idleRounds = 0;

    for (let round = 1; round <= OPTIONS.maxLoadRounds; round++) {
      const before = pageSnapshot();
      const button = findLoadMoreButton();
      if (button) {
        button.scrollIntoView({ block: "center" });
        button.click();
      }
      scrollEverythingDown();
      await sleep(OPTIONS.waitAfterLoadMs);
      scanPage();

      log(`Load more round ${round}: ${gifUrls.size} GIF URL ab tak${button ? " (button click kiya)" : ""}`);
      if (gifUrls.size >= enough) {
        break;
      }
      idleRounds = pageSnapshot() === before ? idleRounds + 1 : 0;
      if (idleRounds >= OPTIONS.idleRoundsToStop) {
        log("Page par mazeed content nahi aa raha, load more band.");
        break;
      }
    }
    window.scrollTo(0, 0);
  };

  const isGifBytes = (bytes) => {
    return bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38;
  };

  const fetchBytes = async (url) => {
    const sameOrigin = url.startsWith("data:") || new URL(url).origin === location.origin;
    const response = await fetch(url, {
      credentials: sameOrigin ? "include" : "omit",
      mode: "cors",
      cache: "force-cache",
    });
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    return new Uint8Array(await response.arrayBuffer());
  };

  const usedNames = new Map();
  let inlineCount = 0;

  const baseNameFor = (url) => {
    if (url.startsWith("data:")) {
      inlineCount += 1;
      return `inline-${inlineCount}`;
    }
    const lastSegment = new URL(url).pathname.split("/").filter(Boolean).pop() || "image";
    let decoded = lastSegment;
    try {
      decoded = decodeURIComponent(lastSegment);
    } catch {
      decoded = lastSegment;
    }
    return decoded.replace(/\.gif$/i, "");
  };

  const fileNameFor = (url) => {
    const safe = baseNameFor(url).replace(/[\\/:*?"<>|\x00-\x1f]/g, "_").slice(0, 120) || "image";
    const key = safe.toLowerCase();
    const seen = usedNames.get(key) || 0;
    usedNames.set(key, seen + 1);
    return seen ? `${safe}-${seen}.gif` : `${safe}.gif`;
  };

  const downloadAll = async (candidates) => {
    const files = [];
    const failed = [];
    const queue = [...candidates];
    let done = 0;

    const handleOne = async (url) => {
      try {
        const bytes = await fetchBytes(url);
        if (isGifBytes(bytes)) {
          files.push({ name: fileNameFor(url), data: bytes });
        } else if (gifUrls.has(url)) {
          failed.push({ url, reason: "file asal mein GIF nahi hai" });
        }
      } catch (err) {
        failed.push({ url, reason: err.message || String(err) });
      }
      done += 1;
      if (done % 5 === 0 || done === candidates.length) {
        log(`${done}/${candidates.length} check ho gayin`);
      }
    };

    const worker = async () => {
      while (queue.length && files.length < OPTIONS.maxGifs) {
        await handleOne(queue.shift());
      }
    };

    await Promise.all(Array.from({ length: OPTIONS.concurrency }, worker));
    return { files: files.slice(0, OPTIONS.maxGifs), failed };
  };

  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);
  };

  const askCount = (thing, fallback) => {
    const answer = window.prompt(`Kitni ${thing} chahiye? Number likho, ya "all" likho sab ke liye.`, String(fallback));
    if (answer === null) {
      return null;
    }
    const text = answer.trim().toLowerCase();
    if (["all", "sab", "sari", "saari", "0"].includes(text)) {
      return Infinity;
    }
    const count = Number.parseInt(text, 10);
    return Number.isFinite(count) && count > 0 ? count : NaN;
  };

  const requested = OPTIONS.askForCount ? askCount("GIFs", OPTIONS.maxGifs) : OPTIONS.maxGifs;
  if (requested === null) {
    log("Cancel kar diya.");
    return;
  }
  if (Number.isNaN(requested)) {
    log("Sahi number nahi likha, script dobara chalao.");
    return;
  }
  OPTIONS.maxGifs = requested;
  const limitLabel = requested === Infinity ? "saari" : `max ${requested}`;

  scanPage();
  if (OPTIONS.autoLoadMore) {
    log(`Page ko load more kar raha hoon (${limitLabel} GIFs)...`);
    await autoLoad();
  }

  const candidates = [...gifUrls, ...(OPTIONS.sniffAllImages ? otherImageUrls : [])];
  if (!candidates.length) {
    log("Is page par koi GIF nahi mili. Agar URLs mein .gif nahi likha, to OPTIONS.sniffAllImages = true kar ke dobara chalao.");
    return;
  }

  const extra = OPTIONS.sniffAllImages ? ` + ${otherImageUrls.size} doosri images check hongi` : "";
  log(`${gifUrls.size} GIF URL mile${extra}. Download shuru...`);

  const { files, failed } = await downloadAll(candidates);
  if (!files.length) {
    log("Koi GIF download nahi ho saki.");
    console.table(failed);
    return;
  }

  const totalBytes = files.reduce((sum, file) => sum + file.data.length, 0);
  if (totalBytes > 0xfffffff0 || files.length > 0xffff) {
    log("Data 4 GB ya 65535 files se zyada hai, page ko hisson mein chalao.");
    return;
  }

  saveBlob(new Blob(buildZip(files), { type: "application/zip" }), OPTIONS.zipName);
  log(`Ho gaya: ${files.length} GIFs, ${(totalBytes / 1024 / 1024).toFixed(2)} MB -> ${OPTIONS.zipName}`);

  if (failed.length) {
    log(`${failed.length} file(s) nahi aa sakin (aksar doosre domain ka CORS block):`);
    console.table(failed);
  }
})();
Overview

What GIF ZIP Downloader does

A single console snippet that finds every GIF on the page you are looking at, including lazy-loaded images, srcset, CSS backgrounds, pseudo-elements, shadow DOM and anything already fetched over the network. It asks how many you want, clicks Load more buttons and scrolls infinite feeds until it has enough, checks each file really is a GIF by its bytes, and saves them as one ZIP built right in the browser with no library. Tweak the OPTIONS block at the top to change the limit, turn off auto loading, raise concurrency or sniff images whose URLs hide the .gif extension. Files blocked by another site's CORS rules are listed in the console instead of failing silently.

Release history

  1. v1.0.0

    GIF ZIP Downloader added to the hub

    Paste into the browser console and download every GIF on a page as one ZIP.