doracoin gist felülvizsgálása . Revízióhoz ugrás
1 file changed, 2 insertions, 1 deletion
wechat-article-image-downloader.user.js
| @@ -1,12 +1,13 @@ | |||
| 1 | 1 | // ==UserScript== | |
| 2 | 2 | // @name 微信公众号文章图片批量下载 | |
| 3 | 3 | // @namespace local.wechat-article-image-downloader | |
| 4 | - | // @version 1.2.0 | |
| 4 | + | // @version 1.2.1 | |
| 5 | 5 | // @description 将微信公众号文章和图文轮播中的图片及链接信息下载到标题文件夹。 | |
| 6 | 6 | // @match https://mp.weixin.qq.com/s/* | |
| 7 | 7 | // @match https://mp.weixin.qq.com/s?* | |
| 8 | 8 | // @run-at document-idle | |
| 9 | 9 | // @grant GM_download | |
| 10 | + | // @icon https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico | |
| 10 | 11 | // @connect qpic.cn | |
| 11 | 12 | // ==/UserScript== | |
| 12 | 13 | ||
doracoin gist felülvizsgálása . Revízióhoz ugrás
2 files changed, 115 insertions, 26 deletions
Readme.md(fájl létrehozva)
| @@ -0,0 +1,26 @@ | |||
| 1 | + | # 微信公众号文章图片批量下载 | |
| 2 | + | ||
| 3 | + | 一个 Tampermonkey 用户脚本,用于在微信公众号文章页批量下载正文图片、GIF,以及“图文”模式左右滑动轮播中的图片。 | |
| 4 | + | ||
| 5 | + | ## 安装 | |
| 6 | + | ||
| 7 | + | 1. 安装 Tampermonkey 浏览器扩展。 | |
| 8 | + | 2. 新建脚本,将 [`wechat-article-image-downloader.user.js`](./wechat-article-image-downloader.user.js) 全部内容粘贴进去并保存。 | |
| 9 | + | 3. 打开 `https://mp.weixin.qq.com/s/...` 文章页,页面右下角会出现“文章图片下载”面板。 | |
| 10 | + | 4. 点击“下载全部图片 / GIF”。脚本会在浏览器下载目录下创建以文章标题命名的文件夹,图片和 `info.txt` 都放在该文件夹内。浏览器可能会询问是否允许此站点批量下载,请允许。 | |
| 11 | + | 5. 如果 Tampermonkey 提示文件扩展名未获准,在扩展设置中允许 `txt`、`jpg`、`png`、`gif`、`webp`、`bmp` 文件类型。 | |
| 12 | + | ||
| 13 | + | ## 图片地址与文件名 | |
| 14 | + | ||
| 15 | + | 普通文章图片按 `data-croporisrc`、`data-src`、`data-original`、`data-lazy-src`、`src` 的顺序读取地址。图文轮播模式会额外读取 `.swiper_item[data-src]`;该容器地址优先于子级 `<img src>`,因为后者可能是 `tp=webp` 预览图。对 `mmbiz.qpic.cn` 地址,脚本会将路径中的 `/640` 改为微信常见的原图路径 `/0`,并清除 `tp=webp` 等页面预览参数;图片格式从 `wx_fmt` 或图片元素的 `data-type` 推断。因此 GIF 按 `.gif` 下载,不会被页面的 WebP 预览地址变成静态图。 | |
| 16 | + | ||
| 17 | + | 文件名使用“文章标题_序号.扩展名”,例如 `大肥鱼表情包_001.gif`。重复地址只下载一次。页面动态加载或轮播切换后新发现的地址会加入本次图片列表。 | |
| 18 | + | ||
| 19 | + | 每次批量下载会生成 `info.txt`,记录文章标题、当前文章链接、导出时间,以及每张图片的文件名、源地址和下载结果。文件夹和文件名会清理 Windows 不支持的字符。 | |
| 20 | + | ||
| 21 | + | ## 使用边界 | |
| 22 | + | ||
| 23 | + | - 页面里已经加载或写入 DOM 的正文图片和轮播项会被扫描;动态插入或轮播切换后新发现的图片会在面板计数刷新时纳入。 | |
| 24 | + | - 微信 CDN 的地址规则可能变化;如果个别图片下载失败,可检查浏览器控制台和 Tampermonkey 的下载权限。 | |
| 25 | + | - `info.txt` 通过 Tampermonkey 的 Blob 下载接口生成;请使用支持 Blob 下载的 Tampermonkey 版本(5.4.6226 或更新版本)。 | |
| 26 | + | - 脚本处理文章正文中的 `<img>` 和 `.swiper_item[data-src]`,不处理视频封面、CSS 背景图或文章内嵌的其他文件。若轮播采用虚拟列表,只将当前页放入 DOM,建议先左右浏览一次各页,让脚本发现其图片地址。 | |
wechat-article-image-downloader.user.js
| @@ -1,8 +1,8 @@ | |||
| 1 | 1 | // ==UserScript== | |
| 2 | 2 | // @name 微信公众号文章图片批量下载 | |
| 3 | 3 | // @namespace local.wechat-article-image-downloader | |
| 4 | - | // @version 1.0.0 | |
| 5 | - | // @description 批量下载微信公众号文章中的图片和 GIF,并按文章标题与序号命名。 | |
| 4 | + | // @version 1.2.0 | |
| 5 | + | // @description 将微信公众号文章和图文轮播中的图片及链接信息下载到标题文件夹。 | |
| 6 | 6 | // @match https://mp.weixin.qq.com/s/* | |
| 7 | 7 | // @match https://mp.weixin.qq.com/s?* | |
| 8 | 8 | // @run-at document-idle | |
| @@ -22,6 +22,7 @@ | |||
| 22 | 22 | 'data-lazy-src', | |
| 23 | 23 | 'src', | |
| 24 | 24 | ]; | |
| 25 | + | const discoveredImages = new Map(); | |
| 25 | 26 | ||
| 26 | 27 | const sleep = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)); | |
| 27 | 28 | ||
| @@ -44,9 +45,9 @@ | |||
| 44 | 45 | .slice(0, 100); | |
| 45 | 46 | } | |
| 46 | 47 | ||
| 47 | - | function getImageType(img, url) { | |
| 48 | + | function getImageType(mediaNode, url) { | |
| 48 | 49 | const params = new URL(url).searchParams; | |
| 49 | - | const format = (params.get('wx_fmt') || img.dataset.type || '').toLowerCase(); | |
| 50 | + | const format = (params.get('wx_fmt') || mediaNode.dataset.type || '').toLowerCase(); | |
| 50 | 51 | if (format === 'jpg' || format === 'jpeg') return 'jpg'; | |
| 51 | 52 | if (format === 'png' || format === 'gif' || format === 'webp' || format === 'bmp') return format; | |
| 52 | 53 | ||
| @@ -56,7 +57,7 @@ | |||
| 56 | 57 | return 'jpg'; | |
| 57 | 58 | } | |
| 58 | 59 | ||
| 59 | - | function normalizeImageUrl(rawUrl, img) { | |
| 60 | + | function normalizeImageUrl(rawUrl, mediaNode) { | |
| 60 | 61 | if (!rawUrl || rawUrl.startsWith('data:') || rawUrl.startsWith('blob:')) return null; | |
| 61 | 62 | ||
| 62 | 63 | let url; | |
| @@ -72,42 +73,53 @@ | |||
| 72 | 73 | url.pathname = url.pathname.replace(/\/640(?=\/|$)/, '/0'); | |
| 73 | 74 | } | |
| 74 | 75 | ||
| 75 | - | const type = (url.searchParams.get('wx_fmt') || img.dataset.type || '').toLowerCase(); | |
| 76 | + | const type = (url.searchParams.get('wx_fmt') || mediaNode.dataset.type || '').toLowerCase(); | |
| 76 | 77 | if (['gif', 'png', 'jpeg', 'jpg', 'webp'].includes(type)) { | |
| 77 | 78 | url.searchParams.set('wx_fmt', type === 'jpg' ? 'jpeg' : type); | |
| 78 | 79 | } | |
| 79 | 80 | ||
| 80 | 81 | // 去掉微信页面给预览图添加的格式转换和懒加载标记,避免 GIF 被转成静态 WebP。 | |
| 81 | 82 | ['tp', 'wxfrom', 'wx_lazy', 'wx_co'].forEach((key) => url.searchParams.delete(key)); | |
| 83 | + | // 不同节点可能以不同顺序排列相同的查询参数;排序后才能正确去重。 | |
| 84 | + | url.searchParams.sort(); | |
| 82 | 85 | url.hash = ''; | |
| 83 | 86 | return url.href; | |
| 84 | 87 | } | |
| 85 | 88 | ||
| 86 | 89 | function collectImages() { | |
| 87 | - | const seen = new Set(); | |
| 88 | - | const images = []; | |
| 90 | + | const root = articleRoot(); | |
| 91 | + | const mediaNodes = Array.from(root.querySelectorAll('img, .swiper_item[data-src]')); | |
| 89 | 92 | ||
| 90 | - | articleRoot().querySelectorAll('img').forEach((img) => { | |
| 93 | + | // 某些图文模式把轮播组件放在 #js_content 之外;只补充轮播容器,避免扫入头像等页面图片。 | |
| 94 | + | document.querySelectorAll('.swiper_item[data-src]').forEach((item) => { | |
| 95 | + | if (!root.contains(item)) mediaNodes.push(item); | |
| 96 | + | }); | |
| 97 | + | ||
| 98 | + | mediaNodes.forEach((mediaNode) => { | |
| 91 | 99 | let rawUrl = ''; | |
| 92 | - | for (const attribute of SOURCE_ATTRIBUTES) { | |
| 93 | - | const candidate = img.getAttribute(attribute); | |
| 94 | - | if (candidate && !candidate.startsWith('data:image/')) { | |
| 95 | - | rawUrl = candidate; | |
| 96 | - | break; | |
| 100 | + | if (mediaNode.matches('.swiper_item[data-src]')) { | |
| 101 | + | // 轮播容器的 data-src 通常是 /0 原图;子级 img.src 可能是 tp=webp 预览图。 | |
| 102 | + | rawUrl = mediaNode.getAttribute('data-src') || ''; | |
| 103 | + | } else { | |
| 104 | + | for (const attribute of SOURCE_ATTRIBUTES) { | |
| 105 | + | const candidate = mediaNode.getAttribute(attribute); | |
| 106 | + | if (candidate && !candidate.startsWith('data:image/')) { | |
| 107 | + | rawUrl = candidate; | |
| 108 | + | break; | |
| 109 | + | } | |
| 97 | 110 | } | |
| 98 | 111 | } | |
| 99 | 112 | ||
| 100 | - | const url = normalizeImageUrl(rawUrl, img); | |
| 101 | - | if (!url || seen.has(url)) return; | |
| 102 | - | seen.add(url); | |
| 113 | + | const url = normalizeImageUrl(rawUrl, mediaNode); | |
| 114 | + | if (!url || discoveredImages.has(url)) return; | |
| 103 | 115 | ||
| 104 | - | images.push({ | |
| 116 | + | discoveredImages.set(url, { | |
| 105 | 117 | url, | |
| 106 | - | extension: getImageType(img, url), | |
| 118 | + | extension: getImageType(mediaNode, url), | |
| 107 | 119 | }); | |
| 108 | 120 | }); | |
| 109 | 121 | ||
| 110 | - | return images; | |
| 122 | + | return Array.from(discoveredImages.values()); | |
| 111 | 123 | } | |
| 112 | 124 | ||
| 113 | 125 | function downloadOne(url, name) { | |
| @@ -128,6 +140,29 @@ | |||
| 128 | 140 | }); | |
| 129 | 141 | } | |
| 130 | 142 | ||
| 143 | + | function createInfoFile(title, images, results) { | |
| 144 | + | const exportedAt = new Date().toLocaleString('zh-CN', { | |
| 145 | + | dateStyle: 'long', | |
| 146 | + | timeStyle: 'medium', | |
| 147 | + | }); | |
| 148 | + | const lines = [ | |
| 149 | + | `标题:${title}`, | |
| 150 | + | `文章链接:${location.href}`, | |
| 151 | + | `导出时间:${exportedAt}`, | |
| 152 | + | `图片总数:${images.length}`, | |
| 153 | + | '', | |
| 154 | + | '图片清单:', | |
| 155 | + | ]; | |
| 156 | + | ||
| 157 | + | results.forEach((result) => { | |
| 158 | + | lines.push(`- ${result.filename} [${result.success ? '下载成功' : '下载失败'}]`); | |
| 159 | + | lines.push(` 图片地址:${result.url}`); | |
| 160 | + | if (result.error) lines.push(` 失败原因:${result.error}`); | |
| 161 | + | }); | |
| 162 | + | ||
| 163 | + | return new Blob([`\uFEFF${lines.join('\n')}\n`], { type: 'text/plain;charset=utf-8' }); | |
| 164 | + | } | |
| 165 | + | ||
| 131 | 166 | function addPanel() { | |
| 132 | 167 | if (document.getElementById(PANEL_ID)) return; | |
| 133 | 168 | ||
| @@ -187,32 +222,60 @@ | |||
| 187 | 222 | let succeeded = 0; | |
| 188 | 223 | let failed = 0; | |
| 189 | 224 | const title = articleTitle(); | |
| 225 | + | const folderName = title; | |
| 226 | + | const results = []; | |
| 190 | 227 | ||
| 191 | 228 | for (let index = 0; index < images.length; index += 1) { | |
| 192 | 229 | const image = images[index]; | |
| 193 | 230 | const number = String(index + 1).padStart(3, '0'); | |
| 194 | - | const filename = `${title}_${number}.${image.extension}`; | |
| 195 | - | status.textContent = `正在下载 ${index + 1}/${images.length}:${filename}`; | |
| 231 | + | const filename = `${folderName}/${title}_${number}.${image.extension}`; | |
| 232 | + | status.textContent = `正在下载 ${index + 1}/${images.length}:${title}_${number}.${image.extension}`; | |
| 196 | 233 | try { | |
| 197 | 234 | await downloadOne(image.url, filename); | |
| 198 | 235 | succeeded += 1; | |
| 236 | + | results.push({ filename: `${title}_${number}.${image.extension}`, url: image.url, success: true }); | |
| 199 | 237 | } catch (error) { | |
| 200 | 238 | failed += 1; | |
| 201 | 239 | console.warn('[微信文章图片下载]', filename, error); | |
| 240 | + | results.push({ | |
| 241 | + | filename: `${title}_${number}.${image.extension}`, | |
| 242 | + | url: image.url, | |
| 243 | + | success: false, | |
| 244 | + | error: error.message, | |
| 245 | + | }); | |
| 202 | 246 | } | |
| 203 | 247 | if (index < images.length - 1) await sleep(DOWNLOAD_GAP_MS); | |
| 204 | 248 | } | |
| 205 | 249 | ||
| 250 | + | let infoSaved = false; | |
| 251 | + | try { | |
| 252 | + | status.textContent = '正在保存文章链接和图片清单…'; | |
| 253 | + | await downloadOne(createInfoFile(title, images, results), `${folderName}/info.txt`); | |
| 254 | + | infoSaved = true; | |
| 255 | + | } catch (error) { | |
| 256 | + | console.warn('[微信文章图片下载] info.txt', error); | |
| 257 | + | } | |
| 258 | + | ||
| 206 | 259 | status.textContent = failed | |
| 207 | - | ? `完成:成功 ${succeeded} 张,失败 ${failed} 张。可查看控制台了解失败原因。` | |
| 208 | - | : `下载完成:${succeeded} 张。`; | |
| 260 | + | ? `图片成功 ${succeeded} 张,失败 ${failed} 张;${infoSaved ? 'info.txt 已保存' : 'info.txt 保存失败'}。` | |
| 261 | + | : `下载完成:${succeeded} 张;${infoSaved ? 'info.txt 已保存' : 'info.txt 保存失败'}。`; | |
| 209 | 262 | downloadButton.disabled = false; | |
| 210 | 263 | }); | |
| 211 | 264 | ||
| 212 | 265 | refreshCount(); | |
| 213 | 266 | // 兼容微信文章图片延迟插入正文的情况。 | |
| 214 | - | const observer = new MutationObserver(refreshCount); | |
| 215 | - | observer.observe(articleRoot(), { childList: true, subtree: true }); | |
| 267 | + | let refreshTimer; | |
| 268 | + | const observer = new MutationObserver((mutations) => { | |
| 269 | + | if (!mutations.some((mutation) => !panel.contains(mutation.target))) return; | |
| 270 | + | window.clearTimeout(refreshTimer); | |
| 271 | + | refreshTimer = window.setTimeout(refreshCount, 150); | |
| 272 | + | }); | |
| 273 | + | observer.observe(document.body, { | |
| 274 | + | childList: true, | |
| 275 | + | subtree: true, | |
| 276 | + | attributes: true, | |
| 277 | + | attributeFilter: ['data-src', 'src'], | |
| 278 | + | }); | |
| 216 | 279 | window.setTimeout(() => observer.disconnect(), 30000); | |
| 217 | 280 | } | |
| 218 | 281 | ||
doracoin gist felülvizsgálása . Revízióhoz ugrás
1 file changed, 221 insertions
wechat-article-image-downloader.user.js(fájl létrehozva)
| @@ -0,0 +1,221 @@ | |||
| 1 | + | // ==UserScript== | |
| 2 | + | // @name 微信公众号文章图片批量下载 | |
| 3 | + | // @namespace local.wechat-article-image-downloader | |
| 4 | + | // @version 1.0.0 | |
| 5 | + | // @description 批量下载微信公众号文章中的图片和 GIF,并按文章标题与序号命名。 | |
| 6 | + | // @match https://mp.weixin.qq.com/s/* | |
| 7 | + | // @match https://mp.weixin.qq.com/s?* | |
| 8 | + | // @run-at document-idle | |
| 9 | + | // @grant GM_download | |
| 10 | + | // @connect qpic.cn | |
| 11 | + | // ==/UserScript== | |
| 12 | + | ||
| 13 | + | (function () { | |
| 14 | + | 'use strict'; | |
| 15 | + | ||
| 16 | + | const PANEL_ID = 'wx-image-downloader-panel'; | |
| 17 | + | const DOWNLOAD_GAP_MS = 350; | |
| 18 | + | const SOURCE_ATTRIBUTES = [ | |
| 19 | + | 'data-croporisrc', | |
| 20 | + | 'data-src', | |
| 21 | + | 'data-original', | |
| 22 | + | 'data-lazy-src', | |
| 23 | + | 'src', | |
| 24 | + | ]; | |
| 25 | + | ||
| 26 | + | const sleep = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)); | |
| 27 | + | ||
| 28 | + | function articleRoot() { | |
| 29 | + | return document.querySelector('#js_content') || document.querySelector('article') || document.body; | |
| 30 | + | } | |
| 31 | + | ||
| 32 | + | function articleTitle() { | |
| 33 | + | const title = document.querySelector('#activity-name')?.textContent | |
| 34 | + | || document.querySelector('meta[property="og:title"]')?.content | |
| 35 | + | || document.title | |
| 36 | + | || '微信公众号文章'; | |
| 37 | + | return sanitizeFilename(title.trim().replace(/\s+/g, ' ')) || '微信公众号文章'; | |
| 38 | + | } | |
| 39 | + | ||
| 40 | + | function sanitizeFilename(value) { | |
| 41 | + | return value | |
| 42 | + | .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_') | |
| 43 | + | .replace(/[. ]+$/g, '') | |
| 44 | + | .slice(0, 100); | |
| 45 | + | } | |
| 46 | + | ||
| 47 | + | function getImageType(img, url) { | |
| 48 | + | const params = new URL(url).searchParams; | |
| 49 | + | const format = (params.get('wx_fmt') || img.dataset.type || '').toLowerCase(); | |
| 50 | + | if (format === 'jpg' || format === 'jpeg') return 'jpg'; | |
| 51 | + | if (format === 'png' || format === 'gif' || format === 'webp' || format === 'bmp') return format; | |
| 52 | + | ||
| 53 | + | const extension = new URL(url).pathname.match(/\.([a-z\d]+)$/i)?.[1]?.toLowerCase(); | |
| 54 | + | if (extension === 'jpeg') return 'jpg'; | |
| 55 | + | if (['jpg', 'png', 'gif', 'webp', 'bmp'].includes(extension)) return extension; | |
| 56 | + | return 'jpg'; | |
| 57 | + | } | |
| 58 | + | ||
| 59 | + | function normalizeImageUrl(rawUrl, img) { | |
| 60 | + | if (!rawUrl || rawUrl.startsWith('data:') || rawUrl.startsWith('blob:')) return null; | |
| 61 | + | ||
| 62 | + | let url; | |
| 63 | + | try { | |
| 64 | + | url = new URL(rawUrl, location.href); | |
| 65 | + | } catch { | |
| 66 | + | return null; | |
| 67 | + | } | |
| 68 | + | ||
| 69 | + | if (!/^https?:$/.test(url.protocol)) return null; | |
| 70 | + | if (/mmbiz\.qpic\.cn$/i.test(url.hostname)) { | |
| 71 | + | // /0 是微信图片常见的原图地址;/640 是文章正文中的缩放图地址。 | |
| 72 | + | url.pathname = url.pathname.replace(/\/640(?=\/|$)/, '/0'); | |
| 73 | + | } | |
| 74 | + | ||
| 75 | + | const type = (url.searchParams.get('wx_fmt') || img.dataset.type || '').toLowerCase(); | |
| 76 | + | if (['gif', 'png', 'jpeg', 'jpg', 'webp'].includes(type)) { | |
| 77 | + | url.searchParams.set('wx_fmt', type === 'jpg' ? 'jpeg' : type); | |
| 78 | + | } | |
| 79 | + | ||
| 80 | + | // 去掉微信页面给预览图添加的格式转换和懒加载标记,避免 GIF 被转成静态 WebP。 | |
| 81 | + | ['tp', 'wxfrom', 'wx_lazy', 'wx_co'].forEach((key) => url.searchParams.delete(key)); | |
| 82 | + | url.hash = ''; | |
| 83 | + | return url.href; | |
| 84 | + | } | |
| 85 | + | ||
| 86 | + | function collectImages() { | |
| 87 | + | const seen = new Set(); | |
| 88 | + | const images = []; | |
| 89 | + | ||
| 90 | + | articleRoot().querySelectorAll('img').forEach((img) => { | |
| 91 | + | let rawUrl = ''; | |
| 92 | + | for (const attribute of SOURCE_ATTRIBUTES) { | |
| 93 | + | const candidate = img.getAttribute(attribute); | |
| 94 | + | if (candidate && !candidate.startsWith('data:image/')) { | |
| 95 | + | rawUrl = candidate; | |
| 96 | + | break; | |
| 97 | + | } | |
| 98 | + | } | |
| 99 | + | ||
| 100 | + | const url = normalizeImageUrl(rawUrl, img); | |
| 101 | + | if (!url || seen.has(url)) return; | |
| 102 | + | seen.add(url); | |
| 103 | + | ||
| 104 | + | images.push({ | |
| 105 | + | url, | |
| 106 | + | extension: getImageType(img, url), | |
| 107 | + | }); | |
| 108 | + | }); | |
| 109 | + | ||
| 110 | + | return images; | |
| 111 | + | } | |
| 112 | + | ||
| 113 | + | function downloadOne(url, name) { | |
| 114 | + | return new Promise((resolve, reject) => { | |
| 115 | + | if (typeof GM_download !== 'function') { | |
| 116 | + | reject(new Error('GM_download 不可用,请确认脚本管理器已启用此脚本。')); | |
| 117 | + | return; | |
| 118 | + | } | |
| 119 | + | ||
| 120 | + | GM_download({ | |
| 121 | + | url, | |
| 122 | + | name, | |
| 123 | + | saveAs: false, | |
| 124 | + | onload: resolve, | |
| 125 | + | onerror: (error) => reject(new Error(error?.error || '下载失败')), | |
| 126 | + | ontimeout: () => reject(new Error('请求超时')), | |
| 127 | + | }); | |
| 128 | + | }); | |
| 129 | + | } | |
| 130 | + | ||
| 131 | + | function addPanel() { | |
| 132 | + | if (document.getElementById(PANEL_ID)) return; | |
| 133 | + | ||
| 134 | + | const panel = document.createElement('section'); | |
| 135 | + | panel.id = PANEL_ID; | |
| 136 | + | panel.innerHTML = ` | |
| 137 | + | <div class="wxid-head"> | |
| 138 | + | <strong>文章图片下载</strong> | |
| 139 | + | <button type="button" class="wxid-close" aria-label="收起">−</button> | |
| 140 | + | </div> | |
| 141 | + | <div class="wxid-body"> | |
| 142 | + | <div class="wxid-count"></div> | |
| 143 | + | <button type="button" class="wxid-download">下载全部图片 / GIF</button> | |
| 144 | + | <div class="wxid-status" role="status">GIF 会保留为动态文件。</div> | |
| 145 | + | </div>`; | |
| 146 | + | ||
| 147 | + | const style = document.createElement('style'); | |
| 148 | + | style.textContent = ` | |
| 149 | + | #${PANEL_ID}{position:fixed;z-index:2147483647;right:20px;bottom:24px;width:250px;color:#202124; | |
| 150 | + | background:#fff;border:1px solid #d9dde3;border-radius:10px;box-shadow:0 4px 18px #0002; | |
| 151 | + | font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif} | |
| 152 | + | #${PANEL_ID} .wxid-head{display:flex;align-items:center;justify-content:space-between;padding:10px 12px; | |
| 153 | + | border-bottom:1px solid #eee} | |
| 154 | + | #${PANEL_ID} button{font:inherit;cursor:pointer} | |
| 155 | + | #${PANEL_ID} .wxid-close{border:0;background:transparent;font-size:20px;line-height:1;color:#666} | |
| 156 | + | #${PANEL_ID} .wxid-body{padding:11px 12px 12px} | |
| 157 | + | #${PANEL_ID} .wxid-count{margin-bottom:9px;color:#555} | |
| 158 | + | #${PANEL_ID} .wxid-download{width:100%;padding:8px;border:0;border-radius:6px;background:#07c160;color:white} | |
| 159 | + | #${PANEL_ID} .wxid-download:disabled{cursor:wait;opacity:.65} | |
| 160 | + | #${PANEL_ID} .wxid-status{min-height:20px;margin-top:8px;color:#777;font-size:12px} | |
| 161 | + | #${PANEL_ID}.wxid-collapsed{width:auto} | |
| 162 | + | #${PANEL_ID}.wxid-collapsed .wxid-body{display:none}`; | |
| 163 | + | document.head.append(style); | |
| 164 | + | document.body.append(panel); | |
| 165 | + | ||
| 166 | + | const count = panel.querySelector('.wxid-count'); | |
| 167 | + | const status = panel.querySelector('.wxid-status'); | |
| 168 | + | const downloadButton = panel.querySelector('.wxid-download'); | |
| 169 | + | ||
| 170 | + | const refreshCount = () => { | |
| 171 | + | const total = collectImages().length; | |
| 172 | + | count.textContent = `找到 ${total} 张不重复的图片`; | |
| 173 | + | downloadButton.disabled = total === 0; | |
| 174 | + | if (total === 0) status.textContent = '暂未找到图片,请等待文章内容加载后重试。'; | |
| 175 | + | }; | |
| 176 | + | ||
| 177 | + | panel.querySelector('.wxid-close').addEventListener('click', () => { | |
| 178 | + | panel.classList.toggle('wxid-collapsed'); | |
| 179 | + | panel.querySelector('.wxid-close').textContent = panel.classList.contains('wxid-collapsed') ? '+' : '−'; | |
| 180 | + | }); | |
| 181 | + | ||
| 182 | + | downloadButton.addEventListener('click', async () => { | |
| 183 | + | const images = collectImages(); | |
| 184 | + | if (!images.length) return; | |
| 185 | + | ||
| 186 | + | downloadButton.disabled = true; | |
| 187 | + | let succeeded = 0; | |
| 188 | + | let failed = 0; | |
| 189 | + | const title = articleTitle(); | |
| 190 | + | ||
| 191 | + | for (let index = 0; index < images.length; index += 1) { | |
| 192 | + | const image = images[index]; | |
| 193 | + | const number = String(index + 1).padStart(3, '0'); | |
| 194 | + | const filename = `${title}_${number}.${image.extension}`; | |
| 195 | + | status.textContent = `正在下载 ${index + 1}/${images.length}:${filename}`; | |
| 196 | + | try { | |
| 197 | + | await downloadOne(image.url, filename); | |
| 198 | + | succeeded += 1; | |
| 199 | + | } catch (error) { | |
| 200 | + | failed += 1; | |
| 201 | + | console.warn('[微信文章图片下载]', filename, error); | |
| 202 | + | } | |
| 203 | + | if (index < images.length - 1) await sleep(DOWNLOAD_GAP_MS); | |
| 204 | + | } | |
| 205 | + | ||
| 206 | + | status.textContent = failed | |
| 207 | + | ? `完成:成功 ${succeeded} 张,失败 ${failed} 张。可查看控制台了解失败原因。` | |
| 208 | + | : `下载完成:${succeeded} 张。`; | |
| 209 | + | downloadButton.disabled = false; | |
| 210 | + | }); | |
| 211 | + | ||
| 212 | + | refreshCount(); | |
| 213 | + | // 兼容微信文章图片延迟插入正文的情况。 | |
| 214 | + | const observer = new MutationObserver(refreshCount); | |
| 215 | + | observer.observe(articleRoot(), { childList: true, subtree: true }); | |
| 216 | + | window.setTimeout(() => observer.disconnect(), 30000); | |
| 217 | + | } | |
| 218 | + | ||
| 219 | + | if (document.body) addPanel(); | |
| 220 | + | else document.addEventListener('DOMContentLoaded', addPanel, { once: true }); | |
| 221 | + | })(); | |