リンクのPDFファイルをzipしてダウンロード

  • /*
     * @title リンクのPDFファイルをzipしてダウンロード
     * @description ページ内にある~.PDFというリンクすべてからPDFファイルを取得して、zipして一括ダウンロードします(ドメインの壁は越えられません)。保存名はファイル名またはリンクテキスト.pdfの選択です。
     * @include http://*
     * @license MIT License
     * @javascript_url
     */
    
    
    (async () => {
        const sleep = time => new Promise(resolve => setTimeout(resolve, time));
        await import('https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.0/jszip.min.js');
        const { default: { saveAs } } = await import('https://cdn.jsdelivr.net/npm/file-saver@2.0.5/+esm');
    
        const zip = new JSZip();
    
        const path = 'files' + Number(new Date()) + '/';
    
        async function downloader(element) {
            const response = await fetch(
                element.href,
            );
            element.style.backgroundColor = 'gray';
            const fileName = decodeURIComponent(
                (isUseFileName ?
                    element.href.match(/(?=[^\/]+\.pdf)[^\/]+\.pdf/) :
                    element.textContent.match(/(?=[^\/]+\.pdf)[^\/]+\.pdf/))
                ?? element.textContent.trim() + ".pdf"
            );
            await sleep(2000);
    
            if (zip.file(path + fileName)) { fileName = Number(new Date()) + '_' + fileName };
            zip.file(path + fileName, await response.blob());
    
        };
    
        const isUseFileName = confirm('URLのファイル名で保存します')
    
        for (let target of document.querySelectorAll('a[href*=".pdf"] ')) { await downloader(target).catch(() => { }) };
        for (let target of [...document.querySelectorAll('a:not([href*=".pdf"])')].filter(e => e.textContent.includes('pdf') || e.textContent.includes('PDF'))) { await downloader(target).catch(e => { throw e }) };
        const content = await zip.generateAsync({ type: "blob" });
        saveAs(content, 'files.zip');
    
    })()
  • Permalink
    このページへの個別リンクです。
    RAW
    書かれたコードへの直接のリンクです。
    Packed
    文字列が圧縮された書かれたコードへのリンクです。
    Userscript
    Greasemonkey 等で利用する場合の .user.js へのリンクです。
    Loader
    @require やソースコードが長い場合に多段ロードする Loader コミのコードへのリンクです。
    Metadata
    コード中にコメントで @xxx と書かれたメタデータの JSON です。

History

  1. 2025/01/30 12:15:30 - 01/30
  2. 2025/01/30 12:13:11 - 01/30
  3. 2023/06/30 11:41:04 - 2023-06-30
  4. 2022/05/12 11:57:52 - 2022-05-12
  5. 2022/04/21 17:39:55 - 2022-04-21
  6. 2021/05/11 11:55:06 - 2021-05-11
  7. 2020/10/21 17:59:00 - 2020-10-21
  8. 2020/02/07 14:06:17 - 2020-02-07
  9. 2020/02/05 15:53:15 - 2020-02-05
  10. 2020/02/04 18:07:05 - 2020-02-04
  11. 2020/02/04 17:51:38 - 2020-02-04
  12. 2020/01/11 10:34:49 - 2020-01-11