Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

3.2 KB
Raw Blame
// Runs in the page world: some public attachments are generated by download buttons.
export async function collectPageCaptureDownloads(options = {}) {
  const root = document.querySelector(options.contentSelector || "[data-no-capture-content]");
  if (!root || !options.buttonSelector) return { items: [], failures: 0 };
  const cards = [...root.querySelectorAll(options.containerSelector)];
  const buttons = [...root.querySelectorAll(options.buttonSelector)].slice(0, options.maxMedia);
  const originalClick = HTMLAnchorElement.prototype.click;
  const originalCreate = URL.createObjectURL;
  const blobs = new Map();
  const items = [];
  let pending = null;
  let failures = 0;
  let usedBytes = 0;
  const deadline = Date.now() + options.timeoutMs;
  URL.createObjectURL = function (blob) {
    const url = originalCreate.call(this, blob);
    if (blob instanceof Blob && blob.size <= options.maxBytes) blobs.set(url, blob);
    return url;
  };
  HTMLAnchorElement.prototype.click = function () {
    if (!pending || !this.download) return originalClick.call(this);
    const complete = pending;
    pending = null;
    complete({ filename: this.download, url: this.href, blob: blobs.get(this.href) });
  };
  try {
    for (const button of buttons) {
      const container = button.closest(options.containerSelector);
      const filename = [container?.innerText || "", ...[...(container?.querySelectorAll("span") || [])].map((node) => node.textContent)]
        .flatMap((text) => text.split(/\r?\n/)).map((s) => s.trim())
        .find((s) => options.extensions.some((extension) => s.toLowerCase().endsWith(`.${extension}`)));
      if (!filename) continue;
      if (Date.now() >= deadline) { failures += 1; continue; }
      let timer;
      try {
        const download = await new Promise((resolve, reject) => {
          pending = resolve;
          timer = setTimeout(() => reject(new Error("附件下载动作未完成")), Math.max(0, deadline - Date.now()));
          button.click();
        });
        const index = cards.indexOf(container);
        if (/^https?:/i.test(download.url)) {
          items.push({ index, filename: download.filename, url: download.url });
          continue;
        }
        if (!download.url.startsWith(`blob:${location.origin}/`)) throw new Error("附件来源不可用");
        const blob = download.blob;
        if (!blob || !blob.size || blob.size > options.maxBytes || usedBytes + Math.ceil(blob.size * 4 / 3) > options.maxPayloadBytes) throw new Error("附件超出采集容量或已失效");
        const dataUrl = await new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onload = () => resolve(reader.result);
          reader.onerror = reject;
          reader.readAsDataURL(blob);
        });
        usedBytes += dataUrl.length;
        items.push({ index, filename: download.filename, url: location.href, downloadDataUrl: dataUrl });
      } catch {
        failures += 1;
      } finally {
        clearTimeout(timer);
        pending = null;
        blobs.clear();
      }
    }
  } finally {
    HTMLAnchorElement.prototype.click = originalClick;
    URL.createObjectURL = originalCreate;
  }
  return { items, failures };
}