| 2 | import type { PlasmoMessaging } from "@plasmohq/messaging" |
| 3 | |
| 4 | const handler: PlasmoMessaging.MessageHandler = async (req, res) => { |
| 5 | const { action } = req.body |
| 6 | |
| 7 | if (action === "batchDownloadAllTabs") { |
| 8 | try { |
| 9 | const tabs = await chrome.tabs.query({}) |
| 10 | const supportedSites = [ |
| 11 | { pattern: "mp.weixin.qq.com", name: "weixin" }, |
| 12 | { pattern: "juejin.cn", name: "juejin" }, |
| 13 | { pattern: "csdn.net", name: "csdn" }, |
| 14 | { pattern: "cnblogs.com", name: "cnblogs" }, |
| 15 | { pattern: "jianshu.com", name: "jianshu" }, |
| 16 | { pattern: "segmentfault.com", name: "segmentfault" }, |
| 17 | { pattern: "zhihu.com", name: "zhihu" }, |
| 18 | { pattern: "oschina.net", name: "oschina" }, |
| 19 | { pattern: "51cto.com", name: "51cto" }, |
| 20 | { pattern: "php.net", name: "php" }, |
| 21 | { pattern: "jb51.net", name: "jb51" }, |
| 22 | { pattern: "baidu.com", name: "baidu" } |
| 23 | ] |
| 24 | |
| 25 | const validTabs = tabs.filter((tab) => { |
| 26 | if (!tab.url) return false |
| 27 | return supportedSites.some((site) => tab.url.includes(site.pattern)) |
| 28 | }) |
| 29 | |
| 30 | if (validTabs.length === 0) { |
| 31 | res.send({ code: 0, msg: "没有找到支持的页面" }) |
| 32 | return |
| 33 | } |
| 34 | |
| 35 | const zip = new JSZip() |
| 36 | let successCount = 0 |
| 37 | let failCount = 0 |
| 38 | |
| 39 | for (const tab of validTabs) { |
| 40 | try { |
| 41 | const site = supportedSites.find((s) => tab.url.includes(s.pattern)) |
| 42 | if (!site) continue |
| 43 | |
| 44 | const response = await chrome.tabs.sendMessage(tab.id, { |
| 45 | name: `${site.name}-downloadMarkdown`, |
| 46 | body: { action: "getMarkdown" } |
| 47 | }) |
| 48 | |
| 49 | if (response && response.markdown) { |
| 50 | const title = response.title || `page-${tab.id}` |
| 51 | const safeTitle = title.replace(/[<>:"/\\|?*]/g, "-") |
| 52 | zip.file(`${safeTitle}.md`, response.markdown) |
| 53 | successCount++ |
| 54 | } else { |
| 55 | failCount++ |
| 56 | } |
| 57 | } catch (error) { |
| 58 | console.error(`Failed to download tab ${tab.id}:`, error) |
| 59 | failCount++ |
| 60 | } |
| 61 | } |