diff --git a/plugins/browser-bookmarks-history/CHANGELOG.md b/plugins/browser-bookmarks-history/CHANGELOG.md
index fdb1fbd0f..0726ead2f 100644
--- a/plugins/browser-bookmarks-history/CHANGELOG.md
+++ b/plugins/browser-bookmarks-history/CHANGELOG.md
@@ -1,30 +1,33 @@
# Changelog
+## 2.5.0 - 2026-11-13
+
+- 删除多余指令,改为插件内后缀指令
+- 新增后缀指令说明,输入“-”显示,点击直接填入
+- 新增搜索结果右键菜单
+- 新增本地书签/历史记录删除功能(右键)
+- 搜索结果描述行新增图标,区分 Chrome / Edge
+- 新增历史记录访问时间
+- 修改优化设置页 UI
+- 历史记录去重(同一天同一网址仅一条,跨天保留多条)
+- 修复设置页选择目录/浏览器程序后路径不生效的问题(兼容新版 ztools 异步返回的路径数组)
+- 修复已知bug
## 2.4.1 - 2026-09-05
-修复输入框逻辑
-
-## 2.4.0 - 2026-09-03
-
+- 修复输入框逻辑
- 更新插件图标
- 简化搜索结果描述行,仅保留类型标识(⭐ 书签 / 🕘 历史)与网址
-## 2.3.0 - 2026-09-03
-
-- 新增网站图标显示(读取浏览器本地 Favicons 数据库)
-- 新增 5 个指令:历史记录、chrome书签、chrome历史记录、Edge书签、Edge历史记录
-- 支持按浏览器单独筛选搜索结果
-- 无网站图标时显示浏览器回退图标
-
-## 2.2.0 - 2026-09-03
+## 2.0.0 - 2026-09-03
-- 插件更名为「书签与历史记录搜索」(name: browser-bookmarks-history)
-- 新增浏览器历史记录搜索功能
+- 重写浏览器历史记录搜索功能
- 重写「书签设置」界面,支持便携版 Chrome / Edge 数据目录配置
- 修复便携版 Chrome 书签搜索不到的问题
- 修复点击搜索结果无法打开网页的问题
-## 2.1.2 - 2026-09-03
+## 1.0.0 - 2026-09-03
-- 初始版本:Chrome / Edge 书签搜索
+- 「书签与历史记录搜索」初始版本,一键搜索Chrome/Edge的书签与历史记录
+- 新增「书签设置」界面,支持便携版 Chrome / Edge 数据目录配置
+- 新增网站图标显示(读取浏览器本地 Favicons 数据库)
diff --git a/plugins/browser-bookmarks-history/README.md b/plugins/browser-bookmarks-history/README.md
index 4e9254229..15b1189f2 100644
--- a/plugins/browser-bookmarks-history/README.md
+++ b/plugins/browser-bookmarks-history/README.md
@@ -1,20 +1,36 @@
# 书签与历史记录搜索
-搜索 Chrome / Edge 浏览器的书签与历史记录,支持便携版浏览器。
+一键搜索 Chrome / Edge 浏览器的书签与历史记录,支持便携版浏览器。
-## 指令
+## 特性
-- `书签` — 搜索全部书签 + 历史记录
-- `历史记录` — 仅搜索历史记录
-- `chrome书签` — 仅搜索 Chrome 书签
-- `chrome历史记录` — 仅搜索 Chrome 历史记录
-- `Edge书签` — 仅搜索 Edge 书签
-- `Edge历史记录` — 仅搜索 Edge 历史记录
-- 主窗口直接输入 — 全局联想搜索
-- `书签设置` — 配置便携版 Data 目录、chrome.exe 路径
+- 自动获取网站图标,描述行图标区分书签/历史记录、Chrome / Edge
+- 右键菜单:打开网页、复制链接、默认浏览器打开、打开书签管理器/历史记录页、删除
+- 设置页「书签与历史记录设置」可管理目录与程序
+- 支持日期搜索历史记录,浏览模式逐层查看全部书签
-## 特性
+## 使用说明
+
+1. 输入“书签与历史记录设置”进入设置页配置浏览器
+2. 安装版浏览器会自动配置,若目录为空则手动配置
+3. 配置教程可把鼠标移到标题边上的 !图标,有详细解释
+4. 输入“书签与历史记录搜索”回车输入关键字进行搜索使用
+5. 输入关键字匹配推荐选择“书签与历史记录搜索”进行搜索
+6. 进入插件后在输入框输入指令进行功能搜索,具体指令见下方
+
+## 指令(在插件搜索框中输入)
-- 自动获取网站图标,快速辨别目标网站
-- 书签带 ⭐ 标识,历史记录带 🕘 标识,轻松区分类型
-- 支持便携版 Chrome / Edge 的目录配置,便携版也能搜索
\ No newline at end of file
+- `-ch` — 仅搜索 Chrome 的书签与历史记录
+- `-ed` — 仅搜索 Edge 的书签与历史记录
+- `-b` — 仅搜索书签
+- `-h` — 仅搜索历史记录
+- `-t` — 搜索今天的历史记录
+- `-w` — 搜索最近 7 天的历史记录
+- `-d 20260901-20261001` / `-d 0901` — 搜索指定日期的历史记录
+- `-chb` / `-edb` — 书签浏览模式,按文件夹逐层查看全部书签
+- 输入 `-` 查看全部指令说明
+- 指令可以放在关键词前面或者后面,用空格隔开
+- 不同类型指令可组合(除 `-chb` / `-edb`)
+- 书签指令组合日期无效,书签没有日期
+- 指令都是英文名取首字母,方便记忆,如下
+- ch(chrome) ed(edge) h(history) b(bookmark) t(today) w(week) d(day) chb(chrome bookmark) edb(edge bookmark)
diff --git a/plugins/browser-bookmarks-history/bookmarks.js b/plugins/browser-bookmarks-history/bookmarks.js
index 365f5bc4a..8334ae085 100644
--- a/plugins/browser-bookmarks-history/bookmarks.js
+++ b/plugins/browser-bookmarks-history/bookmarks.js
@@ -1,48 +1,116 @@
const path = require('path')
const fs = require('fs')
+const crypto = require('crypto')
const PROFILES = ['Default', 'Profile 1', 'Profile 2', 'Profile 3', 'Profile 4']
+// 读取单个书签文件的全量条目(兼容传统 Bookmarks 与新版 AccountBookmarks)
+function readBookmarkFile (bookmarkPath, browser) {
+ const bookmarksData = []
+ if (!bookmarkPath) return bookmarksData
+ try { if (!fs.existsSync(bookmarkPath)) return bookmarksData } catch (e) { return bookmarksData }
+ try {
+ const data = JSON.parse(fs.readFileSync(bookmarkPath, 'utf-8'))
+ const getUrlData = (item, folder) => {
+ if (!item || !Array.isArray(item.children)) return
+ item.children.forEach(c => {
+ if (c.type === 'url') {
+ bookmarksData.push({
+ addAt: parseInt(c.date_added) || 0,
+ title: c.name || '',
+ description: (folder ? '「' + folder + '」' : '') + c.url,
+ url: c.url,
+ browser,
+ source: 'bookmark',
+ file: bookmarkPath,
+ guid: c.guid || ''
+ })
+ } else if (c.type === 'folder') {
+ getUrlData(c, folder ? folder + ' - ' + c.name : c.name)
+ }
+ })
+ }
+ if (data && data.roots) {
+ getUrlData(data.roots.bookmark_bar, '')
+ getUrlData(data.roots.other, '')
+ getUrlData(data.roots.synced, '')
+ }
+ } catch (e) {}
+ return bookmarksData
+}
+
function getBookmarks (dataDir, browser) {
const bookmarksData = []
if (!dataDir) return bookmarksData
try { if (!fs.existsSync(dataDir)) return bookmarksData } catch (e) { return bookmarksData }
- for (const profile of PROFILES) {
- const bookmarkPath = path.join(dataDir, profile, 'Bookmarks')
- try { if (!fs.existsSync(bookmarkPath)) continue } catch (e) { continue }
- try {
- const data = JSON.parse(fs.readFileSync(bookmarkPath, 'utf-8'))
- const getUrlData = (item, folder) => {
- if (!item || !Array.isArray(item.children)) return
- item.children.forEach(c => {
- if (c.type === 'url') {
- bookmarksData.push({
- addAt: parseInt(c.date_added) || 0,
- title: c.name || '',
- description: (folder ? '「' + folder + '」' : '') + c.url,
- url: c.url,
- browser,
- source: 'bookmark'
- })
- } else if (c.type === 'folder') {
- getUrlData(c, folder ? folder + ' - ' + c.name : c.name)
- }
- })
- }
- if (data && data.roots) {
- getUrlData(data.roots.bookmark_bar, '')
- getUrlData(data.roots.other, '')
- getUrlData(data.roots.synced, '')
+ // 书签文件兼容新旧两种存储:传统「Bookmarks」文件与新版 Chrome 登录账号后的
+ // 「AccountBookmarks」文件(格式相同:checksum + roots JSON)。
+ // 两者可能并存(Chrome 新版本会在两者中分别保存不同内容):全部读取,
+ // 同一条书签(guid 相同)由 readBookmarksData 的条目级去重合并。
+ const tryReadProfile = (profileDir) => {
+ for (const fn of ['Bookmarks', 'AccountBookmarks']) {
+ const p = path.join(profileDir, fn)
+ if (fs.existsSync(p)) {
+ bookmarksData.push(...readBookmarkFile(p, browser))
}
- } catch (e) {}
+ }
+ }
+ const directOk = fs.existsSync(path.join(dataDir, 'Bookmarks')) || fs.existsSync(path.join(dataDir, 'AccountBookmarks'))
+ if (directOk) {
+ tryReadProfile(dataDir)
+ } else {
+ for (const profile of PROFILES) {
+ tryReadProfile(path.join(dataDir, profile))
+ }
}
return bookmarksData
}
let BOOKMARKS_DATA = []
+// 记录读取过的 Bookmarks 文件路径与修改时间,用于检测浏览器侧新增/修改书签
+let BOOKMARK_FILES = []
+
+function collectBookmarkFiles (dataDir) {
+ const files = []
+ if (!dataDir) return files
+ try { if (!fs.existsSync(dataDir)) return files } catch (e) { return files }
+ // 与 getBookmarks 一致:支持目录直接是 profile(直接含书签文件)或 User Data 根目录;
+ // 兼容传统 Bookmarks 与新版 AccountBookmarks 两种文件名
+ const tryCollect = (profileDir) => {
+ for (const fn of ['Bookmarks', 'AccountBookmarks']) {
+ const p = path.join(profileDir, fn)
+ try {
+ if (fs.existsSync(p)) {
+ files.push({ file: p, mtimeMs: fs.statSync(p).mtimeMs })
+ }
+ } catch (e) {}
+ }
+ }
+ const directOk = fs.existsSync(path.join(dataDir, 'Bookmarks')) || fs.existsSync(path.join(dataDir, 'AccountBookmarks'))
+ if (directOk) {
+ tryCollect(dataDir)
+ } else {
+ for (const profile of PROFILES) {
+ tryCollect(path.join(dataDir, profile))
+ }
+ }
+ return files
+}
function readBookmarksData (appData, extraDirs) {
BOOKMARKS_DATA = []
+ BOOKMARK_FILES = []
+ // 收集所有待读目录(同一目录只读一次)
+ const dirs = []
+ const seenDirs = new Set()
+ const pushDir = (browser, dir) => {
+ if (!dir) return
+ let key
+ try { key = browser + '::' + path.resolve(dir) } catch (e) { key = browser + '::' + dir }
+ if (seenDirs.has(key)) return
+ seenDirs.add(key)
+ dirs.push({ browser, dir })
+ }
let chromeDataDir
let edgeDataDir
if (process.platform === 'win32') {
@@ -53,19 +121,85 @@ function readBookmarksData (appData, extraDirs) {
chromeDataDir = path.join(appDataPath, 'Google/Chrome')
edgeDataDir = path.join(appDataPath, 'Microsoft Edge')
}
- if (chromeDataDir) BOOKMARKS_DATA.push(...getBookmarks(chromeDataDir, 'chrome'))
- if (edgeDataDir) BOOKMARKS_DATA.push(...getBookmarks(edgeDataDir, 'edge'))
+ if (chromeDataDir) pushDir('chrome', chromeDataDir)
+ if (edgeDataDir) pushDir('edge', edgeDataDir)
if (extraDirs) {
const chromeDirs = Array.isArray(extraDirs.chrome) ? extraDirs.chrome : []
const edgeDirs = Array.isArray(extraDirs.edge) ? extraDirs.edge : []
- chromeDirs.forEach(d => BOOKMARKS_DATA.push(...getBookmarks(d, 'chrome')))
- edgeDirs.forEach(d => BOOKMARKS_DATA.push(...getBookmarks(d, 'edge')))
+ chromeDirs.forEach(d => pushDir('chrome', d))
+ edgeDirs.forEach(d => pushDir('edge', d))
+ }
+ // 按「浏览器+文件路径」去重文件:同一文件只完整读取一次(配置里根目录与 Default 目录并存、
+ // 或配置路径与默认路径指向同一文件时,避免同一文件被读两次导致每条重复)
+ const seenFiles = new Set()
+ const fileList = []
+ for (const { browser, dir } of dirs) {
+ for (const f of collectBookmarkFiles(dir)) {
+ let k
+ try { k = browser + '::' + path.resolve(f.file) } catch (e) { k = browser + '::' + f.file }
+ if (seenFiles.has(k)) continue
+ seenFiles.add(k)
+ fileList.push({ browser, file: f.file, mtimeMs: f.mtimeMs })
+ }
+ }
+ // 每个文件读取全量条目(文件夹内书签不会被误删)
+ for (const { browser, file, mtimeMs } of fileList) {
+ BOOKMARKS_DATA.push(...readBookmarkFile(file, browser))
+ BOOKMARK_FILES.push({ file, mtimeMs, browser })
}
+ // 条目级去重:同一浏览器同一书签(guid 相同)只保留一条。
+ // 用于「配置路径」与「默认路径(LOCALAPPDATA 等)」指向同一份数据、但路径不同导致
+ // 文件级去重无法命中时的重复(内容完全相同)。不同 profile 的同名书签 guid 不同,不会被误删。
+ const seenEntries = new Set()
+ BOOKMARKS_DATA = BOOKMARKS_DATA.filter(x => {
+ let k
+ if (x.guid) k = x.browser + '::' + x.guid
+ else k = x.browser + '::' + (x.url || '') + '::' + (x.title || '')
+ if (seenEntries.has(k)) return false
+ seenEntries.add(k)
+ return true
+ })
if (BOOKMARKS_DATA.length > 0) {
BOOKMARKS_DATA = BOOKMARKS_DATA.sort((a, b) => a.addAt - b.addAt)
}
}
+// 检测 Bookmarks 文件是否在浏览器侧发生变化(新增/修改/删除书签)
+function bookmarksChanged () {
+ if (!BOOKMARK_FILES.length) return false
+ for (const f of BOOKMARK_FILES) {
+ try {
+ if (!fs.existsSync(f.file) || fs.statSync(f.file).mtimeMs !== f.mtimeMs) return true
+ } catch (e) {
+ return true
+ }
+ }
+ return false
+}
+
+// ============ 书签文件夹树(浏览模式 -chbk / -edbk) ============
+// 基于已收集的 BOOKMARK_FILES 现读树结构,返回 [{ browser, file, roots: [{key,name,children}] }]
+// 与 Chrome 书签管理器一致:书签栏 / 其他书签 / 移动书签 三个根;节点保留原生结构,
+// folderKey 用 浏览器+根+guid链 稳定标识,供逐层进入与输入框路径编码
+function readBookmarkTree () {
+ const trees = []
+ const rootDefs = [['bookmark_bar', '书签栏'], ['other', '其他书签'], ['synced', '移动书签'], ['mobile', '移动书签']]
+ for (const { file, browser } of BOOKMARK_FILES) {
+ try {
+ const data = JSON.parse(fs.readFileSync(file, 'utf-8'))
+ const roots = []
+ for (const [rk, rn] of rootDefs) {
+ const r = data.roots && data.roots[rk]
+ if (r && Array.isArray(r.children)) {
+ roots.push({ key: browser + '::' + rk, name: rn, children: r.children })
+ }
+ }
+ trees.push({ browser, file, roots })
+ } catch (e) {}
+ }
+ return trees
+}
+
function searchBookmarks (searchWord) {
searchWord = (searchWord || '').trim()
if (!searchWord) return []
@@ -83,4 +217,152 @@ function searchBookmarks (searchWord) {
))
}
-module.exports = { readBookmarksData, searchBookmarks, BOOKMARKS_DATA }
+// ============ 删除书签 ============
+// Chromium BookmarkCodec checksum:MD5 流式拼接 id -> title(utf16le) -> type -> url,
+// 深度优先遍历 bookmark_bar -> other -> synced 三个根目录。
+function computeChecksum (data) {
+ const md5 = crypto.createHash('md5')
+ const updStr = s => md5.update(s, 'utf8')
+ const updU16 = s => md5.update(Buffer.from(s, 'utf16le'))
+ const visit = node => {
+ if (!node || typeof node !== 'object') return
+ const id = String(node.id == null ? '' : node.id)
+ const title = node.name || ''
+ if (node.type === 'url') {
+ updStr(id)
+ updU16(title)
+ updStr('url')
+ updStr(node.url || '')
+ } else {
+ // folder
+ updStr(id)
+ updU16(title)
+ updStr('folder')
+ if (Array.isArray(node.children)) node.children.forEach(visit)
+ }
+ }
+ if (data && data.roots) {
+ visit(data.roots.bookmark_bar)
+ visit(data.roots.other)
+ visit(data.roots.synced)
+ }
+ return md5.digest('hex')
+}
+
+// 删除指定文件中的一个书签(url+title 精确匹配优先,url 兜底)。
+// 新版 Chrome 可能同时存在 Bookmarks 与 AccountBookmarks 两个书签文件(内容不同),
+// 删除时需要从同一个人资料目录下的所有书签文件中删除,否则另一个文件仍保留该书签。
+function deleteBookmarkEntry (file, url, title) {
+ if (!file || !fs.existsSync(file)) return { ok: false, msg: '书签文件不存在:' + file }
+ // 账号同步书签检测:登录浏览器账号(Google / Microsoft)后,账号书签存储在
+ // AccountBookmarks 文件中(顶层含 sync_metadata 同步元数据),由云端同步管理——
+ // 本地删除会被云端恢复,删除必须在浏览器书签管理器中执行(浏览器内删除会同步到云端)。
+ // 仅存在于 Bookmarks 文件(无同步元数据)的为纯本地书签,可正常本地删除。
+ const base = path.basename(file)
+ let synced = false
+ if (base === 'AccountBookmarks') {
+ synced = true
+ } else {
+ try {
+ const head = JSON.parse(fs.readFileSync(file, 'utf-8'))
+ if (head && head.sync_metadata !== undefined) synced = true
+ } catch (e) {}
+ }
+ if (synced) {
+ return { ok: false, synced: true, msg: '该用户已开启书签同步,请到浏览器书签管理器中删除' }
+ }
+ // 同目录下所有书签文件(Bookmarks / AccountBookmarks 中实际存在的)
+ const profileDir = path.dirname(file)
+ const targets = ['Bookmarks', 'AccountBookmarks']
+ .map(fn => path.join(profileDir, fn))
+ .filter(p => fs.existsSync(p))
+ if (!targets.length) targets.push(file)
+ let anyRemoved = false
+ let lastMsg = ''
+ for (const tf of targets) {
+ let raw
+ try {
+ raw = fs.readFileSync(tf, 'utf-8')
+ } catch (e) {
+ lastMsg = '无法读取书签文件:' + (e.message || e)
+ continue
+ }
+ let data
+ try {
+ data = JSON.parse(raw)
+ } catch (e) {
+ lastMsg = '书签文件解析失败:' + (e.message || e)
+ continue
+ }
+ let removed = false
+ const walk = node => {
+ if (!node || !Array.isArray(node.children)) return
+ for (let i = node.children.length - 1; i >= 0; i--) {
+ const c = node.children[i]
+ if (c.type === 'url' && c.url === url) {
+ if (title && c.name !== title) continue
+ node.children.splice(i, 1)
+ removed = true
+ } else if (c.type === 'folder') {
+ walk(c)
+ }
+ }
+ }
+ if (data.roots) {
+ walk(data.roots.bookmark_bar)
+ walk(data.roots.other)
+ walk(data.roots.synced)
+ }
+ if (!removed) continue
+ // 备份 + 重算 checksum + 写回
+ try {
+ fs.copyFileSync(tf, tf + '.bak-' + Date.now())
+ } catch (e) {}
+ data.checksum = computeChecksum(data)
+ // 兼容新版:若原文件存在 checksum_sha256 字段,一并更新(Chromium 用 SHA256 特性时校验)
+ if (data.checksum_sha256) {
+ data.checksum_sha256 = computeChecksumSha256(data)
+ }
+ try {
+ fs.writeFileSync(tf, JSON.stringify(data, null, 2), 'utf-8')
+ anyRemoved = true
+ } catch (e) {
+ lastMsg = '写入书签文件失败(请先关闭浏览器):' + (e.message || e)
+ }
+ }
+ if (anyRemoved) {
+ return { ok: true, msg: '书签已删除' }
+ }
+ if (lastMsg) return { ok: false, msg: lastMsg }
+ return { ok: false, msg: '未找到匹配的书签(可能已被删除)' }
+}
+
+function computeChecksumSha256 (data) {
+ const sha = crypto.createHash('sha256')
+ const updStr = s => sha.update(s, 'utf8')
+ const updU16 = s => sha.update(Buffer.from(s, 'utf16le'))
+ const visit = node => {
+ if (!node || typeof node !== 'object') return
+ const id = String(node.id == null ? '' : node.id)
+ const title = node.name || ''
+ if (node.type === 'url') {
+ updStr(id)
+ updU16(title)
+ updStr('url')
+ updStr(node.url || '')
+ } else {
+ updStr(id)
+ updU16(title)
+ updStr('folder')
+ if (Array.isArray(node.children)) node.children.forEach(visit)
+ }
+ }
+ if (data && data.roots) {
+ visit(data.roots.bookmark_bar)
+ visit(data.roots.other)
+ visit(data.roots.synced)
+ }
+ return sha.digest('hex')
+}
+
+module.exports = { readBookmarksData, searchBookmarks, deleteBookmarkEntry, bookmarksChanged, readBookmarkTree, getBookmarksData: () => BOOKMARKS_DATA }
diff --git a/plugins/browser-bookmarks-history/edge.png b/plugins/browser-bookmarks-history/edge.png
deleted file mode 100644
index 9dc44643d..000000000
Binary files a/plugins/browser-bookmarks-history/edge.png and /dev/null differ
diff --git a/plugins/browser-bookmarks-history/favicons.js b/plugins/browser-bookmarks-history/favicons.js
index 0060ac75f..2a1e57f83 100644
--- a/plugins/browser-bookmarks-history/favicons.js
+++ b/plugins/browser-bookmarks-history/favicons.js
@@ -22,17 +22,33 @@ async function readFavicons (dataDirs) {
const SQL = await getSQL()
const map = new Map()
const tmpFiles = []
+ const seenFiles = new Set()
for (const { browser, dir } of dataDirs) {
if (!dir) continue
try { if (!fs.existsSync(dir)) continue } catch (e) { continue }
- for (const profile of PROFILES) {
- const f = path.join(dir, profile, 'Favicons')
+ // 支持两种配置:目录直接是个人资料目录(Default 本身,直接含 Favicons 文件)
+ // 或 User Data 根目录(含 Default / Profile N 子目录)
+ const candidateDirs = []
+ if (fs.existsSync(path.join(dir, 'Favicons'))) {
+ candidateDirs.push(dir)
+ } else {
+ for (const profile of PROFILES) {
+ if (fs.existsSync(path.join(dir, profile, 'Favicons'))) candidateDirs.push(path.join(dir, profile))
+ }
+ }
+ for (const profileDir of candidateDirs) {
+ const f = path.join(profileDir, 'Favicons')
try { if (!fs.existsSync(f)) continue } catch (e) { continue }
+ // 按文件去重:同一浏览器下同一 Favicons 文件只读一次(与书签/历史去重逻辑一致)
+ let fk
+ try { fk = browser + '::' + path.resolve(f) } catch (e) { fk = browser + '::' + f }
+ if (seenFiles.has(fk)) continue
+ seenFiles.add(fk)
let buf
try {
buf = fs.readFileSync(f)
} catch (e) {
- const tmp = path.join(os.tmpdir(), `zt_fav_${browser}_${profile}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}.db`)
+ const tmp = path.join(os.tmpdir(), `zt_fav_${browser}_${path.basename(profileDir)}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}.db`)
try {
fs.copyFileSync(f, tmp)
tmpFiles.push(tmp)
@@ -42,10 +58,13 @@ async function readFavicons (dataDirs) {
try {
const db = new SQL.Database(buf)
const idToUrl = new Map()
+ // 图标地址:只保留可被界面直接加载的 http(s) 地址;
+ // file:// 等本地缓存路径在 ztools 渲染环境中无法显示(表现为空白),
+ // 丢弃后由 attachFavicon 回退为浏览器图标;http(s) 加载失败时由界面层检测后再回退
const favRows = db.exec('SELECT id, url FROM favicons')
if (favRows && favRows[0]) {
for (const row of favRows[0].values) {
- if (row[0] != null && row[1]) idToUrl.set(row[0], row[1])
+ if (row[0] != null && row[1] && /^https?:\/\//i.test(row[1])) idToUrl.set(row[0], row[1])
}
}
const mapRows = db.exec('SELECT page_url, icon_id FROM icon_mapping')
diff --git a/plugins/browser-bookmarks-history/history.js b/plugins/browser-bookmarks-history/history.js
index 9815417c0..75a5754c1 100644
--- a/plugins/browser-bookmarks-history/history.js
+++ b/plugins/browser-bookmarks-history/history.js
@@ -14,14 +14,88 @@ async function getSQL () {
const PROFILES = ['Default', 'Profile 1', 'Profile 2', 'Profile 3', 'Profile 4']
+// Windows FILETIME(100ns, 1601起) → 毫秒。部分来源的历史库时间单位异常(毫秒/微秒),
+// 标准解释不合理时按其他单位回退,保证 1643 年这类错误不会出现;仍不合理返回 null。
+const MS_FROM_FILETIME = 11644473600000
+function _msInRange (ms) {
+ const d = new Date(ms)
+ return !isNaN(d.getTime()) && d.getFullYear() >= 2000 && d.getFullYear() <= 2100
+}
+function filetimeToMs (ft) {
+ try {
+ const raw = Number(ft)
+ if (!isFinite(raw) || raw <= 0) return null
+ const ms1 = Math.floor(raw / 10000) - MS_FROM_FILETIME
+ if (_msInRange(ms1)) return ms1
+ const ms2 = raw - MS_FROM_FILETIME
+ if (_msInRange(ms2)) return ms2
+ const ms3 = Math.floor(raw / 1000) - MS_FROM_FILETIME
+ if (_msInRange(ms3)) return ms3
+ return null
+ } catch (e) { return null }
+}
+// 毫秒 → 本地日期 YYYY-MM-DD(无效返回空)
+function msToDate (ms) {
+ if (ms == null) return ''
+ const d = new Date(ms)
+ if (isNaN(d.getTime())) return ''
+ const y = d.getFullYear()
+ const m = String(d.getMonth() + 1).padStart(2, '0')
+ const dd = String(d.getDate()).padStart(2, '0')
+ return y + '-' + m + '-' + dd
+}
+function filetimeToDate (ft) {
+ return msToDate(filetimeToMs(ft))
+}
+
+// 跳转中间 URL:浏览器历史页不显示这类跳转链接(Google goto、以及常见统计/跳转网关如
+// api.limestart.cn/backend/counter-v2/redirect、/url、/jump、/redirect 等)
+function isRedirectJump (url) {
+ try {
+ const u = new URL(url)
+ const host = u.hostname || ''
+ // Google 搜索跳转
+ if (/^(www\.)?google\.(com|com\.hk|cn|co\.jp|de|fr|co\.uk|com\.tw)$/i.test(host) &&
+ (u.pathname === '/goto' || u.pathname === '/url' || /^\/url(\/|$)/.test(u.pathname))) {
+ return true
+ }
+ // 通用跳转网关:路径中独立出现 redirect / jump / goto / link 段(如
+ // api.limestart.cn/backend/counter-v2/redirect?name=xxx 这类仅用于计数/中转的链接)
+ const segments = u.pathname.split('/').filter(Boolean)
+ for (const seg of segments) {
+ if (/^(redirect|jump|goto|go|url|link|jumper|forward|proxy)$/i.test(seg)) {
+ // 路径以跳转段结尾(后面只有参数),视为中间跳转链接
+ if (seg === segments[segments.length - 1]) return true
+ }
+ }
+ } catch (e) {}
+ return false
+}
+
function collectHistoryFiles (dataDirs) {
const out = []
+ const seenFiles = new Set()
+ const pushFile = (browser, profile, file) => {
+ if (!file) return
+ let k
+ try { k = browser + '::' + path.resolve(file) } catch (e) { k = browser + '::' + file }
+ if (seenFiles.has(k)) return
+ seenFiles.add(k)
+ out.push({ browser, profile, file })
+ }
for (const { browser, dir } of dataDirs) {
if (!dir) continue
try { if (!fs.existsSync(dir)) continue } catch (e) { continue }
+ // 支持两种配置:目录直接是个人资料目录(Default 本身,直接含 History 文件)
+ // 或 User Data 根目录(含 Default / Profile N 子目录)
+ const direct = path.join(dir, 'History')
+ if (fs.existsSync(direct)) {
+ pushFile(browser, path.basename(dir), direct)
+ continue
+ }
for (const p of PROFILES) {
const h = path.join(dir, p, 'History')
- try { if (fs.existsSync(h)) out.push({ browser, profile: p, file: h }) } catch (e) {}
+ try { if (fs.existsSync(h)) pushFile(browser, p, h) } catch (e) {}
}
}
return out
@@ -29,31 +103,47 @@ function collectHistoryFiles (dataDirs) {
async function readHistory (extraDirs, limit = 3000) {
const dirs = []
+ // 去重:同一数据目录只读取一次。
+ // 安装版浏览器会被自动填入配置(cfg.edgeDirs 等)且默认路径也会无条件读取,两者指向同一目录时
+ // 会导致历史记录条目重复(与书签去重逻辑一致)。
+ const seen = new Set()
+ const push = (browser, dir) => {
+ if (!dir) return
+ let key
+ try { key = browser + '::' + path.resolve(dir) } catch (e) { key = browser + '::' + dir }
+ if (seen.has(key)) return
+ seen.add(key)
+ dirs.push({ browser, dir })
+ }
if (process.platform === 'win32') {
const la = process.env.LOCALAPPDATA
if (la) {
- dirs.push({ browser: 'chrome', dir: path.join(la, 'Google/Chrome/User Data') })
- dirs.push({ browser: 'edge', dir: path.join(la, 'Microsoft/Edge/User Data') })
+ push('chrome', path.join(la, 'Google/Chrome/User Data'))
+ push('edge', path.join(la, 'Microsoft/Edge/User Data'))
}
} else if (process.platform === 'darwin') {
const home = process.env.HOME
if (home) {
- dirs.push({ browser: 'chrome', dir: path.join(home, 'Library/Application Support/Google/Chrome') })
- dirs.push({ browser: 'edge', dir: path.join(home, 'Library/Application Support/Microsoft Edge') })
+ push('chrome', path.join(home, 'Library/Application Support/Google/Chrome'))
+ push('edge', path.join(home, 'Library/Application Support/Microsoft Edge'))
}
}
if (extraDirs) {
const chromeDirs = Array.isArray(extraDirs.chrome) ? extraDirs.chrome : []
const edgeDirs = Array.isArray(extraDirs.edge) ? extraDirs.edge : []
- chromeDirs.forEach(d => dirs.push({ browser: 'chrome', dir: d }))
- edgeDirs.forEach(d => dirs.push({ browser: 'edge', dir: d }))
+ chromeDirs.forEach(d => push('chrome', d))
+ edgeDirs.forEach(d => push('edge', d))
}
const SQL = await getSQL()
- const results = []
+ let results = []
const tmpFiles = []
for (const { browser, profile, file } of collectHistoryFiles(dirs)) {
const tmp = path.join(os.tmpdir(), `zt_bh_hist_${browser}_${profile}_${Date.now()}_${Math.random().toString(36).slice(2, 6)}.db`)
try {
+ // 只复制主数据库文件读取。
+ // 说明:sql.js 从内存字节加载,无法回放 -wal 文件,复制 WAL/SHM 无效;
+ // 且浏览器运行中主库处于 WAL 状态时用字节加载可能报错,导致整个历史读取失败。
+ // 浏览器正常关闭时 Chromium 会把 WAL checkpoint 合并进主库,此时读取完整。
fs.copyFileSync(file, tmp)
tmpFiles.push(tmp)
const db = new SQL.Database(fs.readFileSync(tmp))
@@ -66,14 +156,65 @@ async function readHistory (extraDirs, limit = 3000) {
if (/^(chrome|edge|devtools|view-source|about|brave|vivaldi|opera):/i.test(url)) continue
if (/^(chrome-extension|moz-extension):/i.test(url)) continue
if (!/^https?:/i.test(url)) continue
- results.push({ title, url, visits: row[2] || 0, lastVisit: row[3] || 0, browser, source: 'history' })
+ // 过滤搜索跳转中间 URL(与浏览器历史页显示一致)
+ if (isRedirectJump(url)) continue
+ results.push({ title, url, visits: row[2] || 0, lastVisit: row[3] || 0, browser, source: 'history', file })
}
} finally { db.close() }
} catch (e) {}
}
for (const t of tmpFiles) { try { fs.unlinkSync(t) } catch (e) {} }
+ // 按浏览器历史页的显示逻辑去重:同一天内同一网址只显示最近访问的一条(无论记录在哪个
+ // 个人资料目录/文件里),不同天访问同一网址各保留一条(跨天重复访问是真实历史)。
results.sort((a, b) => (b.lastVisit || 0) - (a.lastVisit || 0))
+ const seenEntries = new Set()
+ results = results.filter(x => {
+ const date = filetimeToDate(x.lastVisit)
+ const k = x.browser + '::' + (x.url || '') + '::' + date
+ if (seenEntries.has(k)) return false
+ seenEntries.add(k)
+ return true
+ })
return results
}
-module.exports = { readHistory }
+// 删除指定 History 数据库文件中匹配 url 的历史记录(含关联的 visits 行)
+async function deleteHistoryEntry (file, url) {
+ if (!file || !fs.existsSync(file)) return { ok: false, msg: '历史数据库不存在:' + file }
+ let SQL
+ try {
+ SQL = await getSQL()
+ } catch (e) {
+ return { ok: false, msg: 'SQL 引擎初始化失败:' + (e.message || e) }
+ }
+ const tmp = path.join(os.tmpdir(), `zt_bh_del_${Date.now()}_${Math.random().toString(36).slice(2, 6)}.db`)
+ try {
+ fs.copyFileSync(file, tmp)
+ const db = new SQL.Database(fs.readFileSync(tmp))
+ try {
+ // visits 表按 url 删除,urls 表按 url 删除
+ db.run('DELETE FROM visits WHERE url = ?', [url])
+ db.run('DELETE FROM urls WHERE url = ?', [url])
+ } catch (e) {
+ db.close()
+ return { ok: false, msg: '删除失败:' + (e.message || e) }
+ }
+ const out = db.export()
+ db.close()
+ try {
+ fs.copyFileSync(file, file + '.bak-' + Date.now())
+ } catch (e) {}
+ try {
+ fs.writeFileSync(file, Buffer.from(out))
+ } catch (e) {
+ return { ok: false, msg: '写入历史数据库失败(请先关闭浏览器):' + (e.message || e) }
+ }
+ return { ok: true, msg: '历史记录已删除' }
+ } catch (e) {
+ return { ok: false, msg: '删除失败:' + (e.message || e) }
+ } finally {
+ try { fs.unlinkSync(tmp) } catch (e) {}
+ }
+}
+
+module.exports = { readHistory, deleteHistoryEntry, collectHistoryFiles, filetimeToMs, msToDate, filetimeToDate }
diff --git a/plugins/browser-bookmarks-history/icons/alert-triangle.svg b/plugins/browser-bookmarks-history/icons/alert-triangle.svg
new file mode 100644
index 000000000..a06c089ff
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/alert-triangle.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/back.svg b/plugins/browser-bookmarks-history/icons/back.svg
new file mode 100644
index 000000000..b2ad2c0f0
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/back.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/bookmark.svg b/plugins/browser-bookmarks-history/icons/bookmark.svg
new file mode 100644
index 000000000..3882c61b4
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/bookmark.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/brand-chrome.svg b/plugins/browser-bookmarks-history/icons/brand-chrome.svg
new file mode 100644
index 000000000..3452f93c8
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/brand-chrome.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/brand-edge.svg b/plugins/browser-bookmarks-history/icons/brand-edge.svg
new file mode 100644
index 000000000..acdb2914a
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/brand-edge.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/check-square.svg b/plugins/browser-bookmarks-history/icons/check-square.svg
new file mode 100644
index 000000000..d4d7e75b1
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/check-square.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/chrome.png b/plugins/browser-bookmarks-history/icons/chrome.png
similarity index 100%
rename from plugins/browser-bookmarks-history/chrome.png
rename to plugins/browser-bookmarks-history/icons/chrome.png
diff --git a/plugins/browser-bookmarks-history/icons/chrome.svg b/plugins/browser-bookmarks-history/icons/chrome.svg
new file mode 100644
index 000000000..d83e7bf1d
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/chrome.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/compass.svg b/plugins/browser-bookmarks-history/icons/compass.svg
new file mode 100644
index 000000000..8cfadbdd9
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/compass.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/copy.svg b/plugins/browser-bookmarks-history/icons/copy.svg
new file mode 100644
index 000000000..93439b391
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/copy.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/cpu.svg b/plugins/browser-bookmarks-history/icons/cpu.svg
new file mode 100644
index 000000000..ce65dbf1e
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/cpu.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/edge.svg b/plugins/browser-bookmarks-history/icons/edge.svg
new file mode 100644
index 000000000..56caadd27
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/edge.svg
@@ -0,0 +1,41 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/edit.svg b/plugins/browser-bookmarks-history/icons/edit.svg
new file mode 100644
index 000000000..8c9071924
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/edit.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/folder.svg b/plugins/browser-bookmarks-history/icons/folder.svg
new file mode 100644
index 000000000..0a320481a
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/folder.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/history.svg b/plugins/browser-bookmarks-history/icons/history.svg
new file mode 100644
index 000000000..90a062a22
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/history.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/home.svg b/plugins/browser-bookmarks-history/icons/home.svg
new file mode 100644
index 000000000..65d46f500
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/home.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/info.svg b/plugins/browser-bookmarks-history/icons/info.svg
new file mode 100644
index 000000000..e8c269eed
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/info.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/logo.png b/plugins/browser-bookmarks-history/icons/logo.png
similarity index 100%
rename from plugins/browser-bookmarks-history/logo.png
rename to plugins/browser-bookmarks-history/icons/logo.png
diff --git a/plugins/browser-bookmarks-history/icons/rotate-right.svg b/plugins/browser-bookmarks-history/icons/rotate-right.svg
new file mode 100644
index 000000000..c3dca09d6
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/rotate-right.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/trash.svg b/plugins/browser-bookmarks-history/icons/trash.svg
new file mode 100644
index 000000000..544158a9b
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/trash.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/icons/x.svg b/plugins/browser-bookmarks-history/icons/x.svg
new file mode 100644
index 000000000..0d5b3fad0
--- /dev/null
+++ b/plugins/browser-bookmarks-history/icons/x.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/index.html b/plugins/browser-bookmarks-history/index.html
new file mode 100644
index 000000000..451eb6083
--- /dev/null
+++ b/plugins/browser-bookmarks-history/index.html
@@ -0,0 +1,18 @@
+
+
+
+
+ 书签与历史记录设置
+
+
+
+
+
+
diff --git a/plugins/browser-bookmarks-history/mcp.js b/plugins/browser-bookmarks-history/mcp.js
index b87979431..74f6a8dcc 100644
--- a/plugins/browser-bookmarks-history/mcp.js
+++ b/plugins/browser-bookmarks-history/mcp.js
@@ -2,9 +2,20 @@
const bookmarks = require('./bookmarks')
const handleBookmarksQuery = async ({ keyword }, ctx) => {
- if (!bookmarks.BOOKMARKS_DATA) bookmarks.readBookmarksData()
+ // 读取插件配置的便携版数据目录(未配置则退回默认路径)
+ let extra = null
+ try {
+ const raw = window.ztools.dbStorage.getItem('bookmarks-config')
+ if (raw) {
+ const cfg = JSON.parse(raw)
+ extra = {
+ chrome: Array.isArray(cfg.chromeDirs) ? cfg.chromeDirs : [],
+ edge: Array.isArray(cfg.edgeDirs) ? cfg.edgeDirs : []
+ }
+ }
+ } catch (e) {}
+ bookmarks.readBookmarksData(null, extra)
const bookmarksResult = bookmarks.searchBookmarks(keyword)
- console.log(bookmarksResult)
// 根据 outputSchema,返回数组,每个元素有 title 和 url
return bookmarksResult.map(b => ({
title: b.title,
@@ -25,4 +36,4 @@ function registerTools() {
module.exports = {
registerTools
-}
\ No newline at end of file
+}
diff --git a/plugins/browser-bookmarks-history/plugin.json b/plugins/browser-bookmarks-history/plugin.json
index ff8b7d53d..8f531f4c3 100644
--- a/plugins/browser-bookmarks-history/plugin.json
+++ b/plugins/browser-bookmarks-history/plugin.json
@@ -1,29 +1,76 @@
{
"preload": "preload.js",
- "logo": "logo.png",
- "platform": ["win32", "darwin"],
- "categories": ["productivity"],
+ "main": "index.html",
+ "logo": "icons/logo.png",
+ "platform": [
+ "win32",
+ "darwin"
+ ],
+ "categories": [
+ "productivity"
+ ],
"author": "ScottLim",
"features": [
- { "code": "all", "explain": "搜索 Chrome / Edge 书签与历史记录", "cmds": ["书签"] },
- { "code": "history", "explain": "搜索 Chrome / Edge 浏览历史记录", "cmds": ["历史记录"] },
- { "code": "chrome_bookmarks", "explain": "仅搜索 Chrome 书签", "cmds": ["chrome书签"] },
- { "code": "chrome_history", "explain": "仅搜索 Chrome 历史记录", "cmds": ["chrome历史记录"] },
- { "code": "edge_bookmarks", "explain": "仅搜索 Edge 书签", "cmds": ["Edge书签"] },
- { "code": "edge_history", "explain": "仅搜索 Edge 历史记录", "cmds": ["Edge历史记录"] },
- { "code": "search", "explain": "书签与历史记录全局搜索", "mainPush": true, "cmds": [{ "type": "over", "maxLength": 40, "label": "书签与历史记录搜索" }] },
- { "code": "settings", "explain": "设置便携版浏览器书签/历史目录", "cmds": ["书签设置"] }
+ {
+ "code": "search",
+ "explain": "书签与历史记录全局搜索",
+ "mainPush": true,
+ "cmds": [
+ "书签与历史记录搜索",
+ {
+ "type": "over",
+ "maxLength": 40,
+ "label": "书签与历史记录搜索"
+ }
+ ]
+ },
+ {
+ "code": "settings",
+ "explain": "为 Chrome / Edge 配置数据目录与程序路径",
+ "cmds": [
+ "书签与历史记录设置"
+ ]
+ }
],
"tools": {
"bookmarks_query": {
"title": "书签搜索",
"description": "在 Chrome、Edge 浏览器的书签中进行搜索",
- "inputSchema": { "type": "object", "additionalProperties": false, "properties": { "keyword": { "type": "string", "description": "搜索关键词" } }, "required": ["keyword"] },
- "outputSchema": { "type": "array", "items": { "type": "object", "properties": { "title": { "type": "string" }, "url": { "type": "string" } }, "required": ["title", "url"] } }
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "keyword": {
+ "type": "string",
+ "description": "搜索关键词"
+ }
+ },
+ "required": [
+ "keyword"
+ ]
+ },
+ "outputSchema": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "url"
+ ]
+ }
+ }
}
},
"name": "browser-bookmarks-history",
"title": "书签与历史记录搜索",
"description": "搜索 Chrome / Edge 浏览器书签与历史记录,支持便携版浏览器",
- "version": "2.4.1"
-}
+ "version": "2.5.0"
+}
\ No newline at end of file
diff --git a/plugins/browser-bookmarks-history/preload.js b/plugins/browser-bookmarks-history/preload.js
index dfa439df2..e3efb4e0a 100644
--- a/plugins/browser-bookmarks-history/preload.js
+++ b/plugins/browser-bookmarks-history/preload.js
@@ -1,14 +1,14 @@
const path = require('path')
const fs = require('fs')
const cp = require('child_process')
-const { readBookmarksData, searchBookmarks } = require('./bookmarks')
-const { readHistory } = require('./history')
+const { readBookmarksData, searchBookmarks, deleteBookmarkEntry, bookmarksChanged, readBookmarkTree, getBookmarksData } = require('./bookmarks')
+const { readHistory, deleteHistoryEntry, collectHistoryFiles, filetimeToMs } = require('./history')
const { readFavicons, getFaviconUrl } = require('./favicons')
const { registerTools } = require('./mcp')
registerTools()
function getConfig () {
- const empty = { chromeDirs: [], edgeDirs: [], chromeExe: '' }
+ const empty = { chromeDirs: [], edgeDirs: [], chromeExe: '', edgeExe: '', autoFilled: {} }
try {
const raw = window.ztools.dbStorage.getItem('bookmarks-config')
if (raw) {
@@ -16,6 +16,8 @@ function getConfig () {
if (Array.isArray(cfg.chromeDirs)) empty.chromeDirs = cfg.chromeDirs.filter(x => typeof x === 'string')
if (Array.isArray(cfg.edgeDirs)) empty.edgeDirs = cfg.edgeDirs.filter(x => typeof x === 'string')
if (typeof cfg.chromeExe === 'string') empty.chromeExe = cfg.chromeExe
+ if (typeof cfg.edgeExe === 'string') empty.edgeExe = cfg.edgeExe
+ if (cfg.autoFilled && typeof cfg.autoFilled === 'object') empty.autoFilled = cfg.autoFilled
}
} catch (e) {}
return empty
@@ -24,26 +26,107 @@ function saveConfig (cfg) {
try { window.ztools.dbStorage.setItem('bookmarks-config', JSON.stringify(cfg)) } catch (e) {}
}
+// 探测系统安装版 Chrome / Edge 的可执行文件与 User Data 目录(存在性校验)
+// 仅返回确认为安装版(exe 与 User Data 都存在)的结果;便携版无固定路径,返回 null
+function detectInstalledBrowsers () {
+ const res = { chrome: null, edge: null }
+ const exists = p => { try { return !!p && fs.existsSync(p) } catch (e) { return false } }
+ if (process.platform === 'win32') {
+ const la = process.env.LOCALAPPDATA
+ const pf = process.env.PROGRAMFILES
+ const pfx = process.env['PROGRAMFILES(X86)']
+ const candidates = (browser) => {
+ if (browser === 'chrome') {
+ const exe = [
+ pfx && path.join(pfx, 'Google/Chrome/Application/chrome.exe'),
+ pf && path.join(pf, 'Google/Chrome/Application/chrome.exe'),
+ la && path.join(la, 'Google/Chrome/Application/chrome.exe')
+ ].find(exists)
+ const data = la && path.join(la, 'Google/Chrome/User Data')
+ return exe && exists(data) ? { exe, dataDir: data } : null
+ }
+ const exe = [
+ pfx && path.join(pfx, 'Microsoft/Edge/Application/msedge.exe'),
+ pf && path.join(pf, 'Microsoft/Edge/Application/msedge.exe'),
+ la && path.join(la, 'Microsoft/Edge/Application/msedge.exe')
+ ].find(exists)
+ const data = la && path.join(la, 'Microsoft/Edge/User Data')
+ return exe && exists(data) ? { exe, dataDir: data } : null
+ }
+ res.chrome = candidates('chrome')
+ res.edge = candidates('edge')
+ } else if (process.platform === 'darwin') {
+ const home = process.env.HOME
+ const chromeExe = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
+ const chromeData = home && path.join(home, 'Library/Application Support/Google/Chrome')
+ if (exists(chromeExe) && exists(chromeData)) res.chrome = { exe: chromeExe, dataDir: chromeData }
+ const edgeExe = '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'
+ const edgeData = home && path.join(home, 'Library/Application Support/Microsoft Edge')
+ if (exists(edgeExe) && exists(edgeData)) res.edge = { exe: edgeExe, dataDir: edgeData }
+ }
+ return res
+}
+
+// 安装版浏览器自动填路径:仅当某浏览器完全未配置(无目录且无 exe)且未被手动清空过时,
+// 把系统安装版的 User Data 目录与 exe 写入配置(便于设置页展示与打开管理页)。
+// 只填路径,不触发重新读取(行为不变)。
+function autoFillInstalledPaths () {
+ try {
+ const cfg = getConfig()
+ const auto = (cfg.autoFilled && typeof cfg.autoFilled === 'object') ? cfg.autoFilled : {}
+ const chromeEmpty = (!cfg.chromeDirs || cfg.chromeDirs.length === 0) && !cfg.chromeExe
+ const edgeEmpty = (!cfg.edgeDirs || cfg.edgeDirs.length === 0) && !cfg.edgeExe
+ if (!(chromeEmpty && !auto.chrome) && !(edgeEmpty && !auto.edge)) return
+ const inst = detectInstalledBrowsers()
+ let changed = false
+ if (chromeEmpty && !auto.chrome && inst.chrome) {
+ cfg.chromeDirs = [inst.chrome.dataDir]
+ cfg.chromeExe = inst.chrome.exe
+ auto.chrome = true
+ changed = true
+ }
+ if (edgeEmpty && !auto.edge && inst.edge) {
+ cfg.edgeDirs = [inst.edge.dataDir]
+ cfg.edgeExe = inst.edge.exe
+ auto.edge = true
+ changed = true
+ }
+ if (changed) {
+ cfg.autoFilled = auto
+ saveConfig(cfg)
+ }
+ } catch (e) {}
+}
+
function buildDataDirs (cfg) {
const dirs = []
+ const seen = new Set()
+ const push = (browser, dir) => {
+ if (!dir) return
+ let key
+ try { key = browser + '::' + path.resolve(dir) } catch (e) { key = browser + '::' + dir }
+ if (seen.has(key)) return
+ seen.add(key)
+ dirs.push({ browser, dir })
+ }
if (process.platform === 'win32') {
const la = process.env.LOCALAPPDATA
if (la) {
- dirs.push({ browser: 'chrome', dir: path.join(la, 'Google/Chrome/User Data') })
- dirs.push({ browser: 'edge', dir: path.join(la, 'Microsoft/Edge/User Data') })
+ push('chrome', path.join(la, 'Google/Chrome/User Data'))
+ push('edge', path.join(la, 'Microsoft/Edge/User Data'))
}
} else if (process.platform === 'darwin') {
const home = process.env.HOME
if (home) {
- dirs.push({ browser: 'chrome', dir: path.join(home, 'Library/Application Support/Google/Chrome') })
- dirs.push({ browser: 'edge', dir: path.join(home, 'Library/Application Support/Microsoft Edge') })
+ push('chrome', path.join(home, 'Library/Application Support/Google/Chrome'))
+ push('edge', path.join(home, 'Library/Application Support/Microsoft Edge'))
}
}
if (cfg) {
const cds = Array.isArray(cfg.chromeDirs) ? cfg.chromeDirs : []
const eds = Array.isArray(cfg.edgeDirs) ? cfg.edgeDirs : []
- cds.forEach(d => dirs.push({ browser: 'chrome', dir: d }))
- eds.forEach(d => dirs.push({ browser: 'edge', dir: d }))
+ cds.forEach(d => push('chrome', d))
+ eds.forEach(d => push('edge', d))
}
return dirs
}
@@ -51,7 +134,8 @@ function buildDataDirs (cfg) {
let bookmarksReady = false
let reloadRequired = true
function ensureBookmarks () {
- if (!bookmarksReady || reloadRequired) {
+ // 浏览器侧 Bookmarks 文件变化(新增/修改/删除书签)时自动重读,无需手动刷新
+ if (!bookmarksReady || reloadRequired || bookmarksChanged()) {
const cfg = getConfig()
readBookmarksData(window.ztools.getPath('appData'), { chrome: cfg.chromeDirs, edge: cfg.edgeDirs })
bookmarksReady = true
@@ -62,14 +146,38 @@ function ensureBookmarks () {
let historyCache = null
let historyTs = 0
let historyLoading = null
+let historySig = '' // 历史数据库文件签名(路径+mtime),文件变化时强制重读
const HISTORY_TTL = 60 * 1000
+
+// 计算历史数据库文件签名:任一 History 主库文件新增/修改/删除都会改变签名
+// (浏览器产生新历史后主库 mtime 变化,重读即可搜到新记录)
+function historyFileSignature () {
+ try {
+ const cfg = getConfig()
+ const files = collectHistoryFiles(buildDataDirs(cfg))
+ const parts = []
+ for (const f of files) {
+ let m = 0
+ try { m = fs.statSync(f.file).mtimeMs } catch (e) { m = -1 }
+ parts.push(f.file + ':' + m)
+ }
+ return parts.sort().join('|')
+ } catch (e) {
+ return ''
+ }
+}
+
function ensureHistory (force) {
- if (!force && historyCache && Date.now() - historyTs < HISTORY_TTL) return Promise.resolve(historyCache)
+ const sig = historyFileSignature()
+ const sigChanged = !!sig && sig !== historySig
+ if (sigChanged) historySig = sig
+ if (!force && !sigChanged && historyCache && Date.now() - historyTs < HISTORY_TTL) return Promise.resolve(historyCache)
if (!historyLoading) {
historyLoading = (async () => {
try {
const cfg = getConfig()
historyCache = await readHistory({ chrome: cfg.chromeDirs, edge: cfg.edgeDirs })
+ historySig = sig || historySig
} catch (e) {
historyCache = historyCache || []
}
@@ -80,7 +188,7 @@ function ensureHistory (force) {
}
return historyLoading
}
-function invalidateHistory () { historyCache = null; historyLoading = null }
+function invalidateHistory () { historyCache = null; historyLoading = null; historySig = '' }
let faviconMap = null
let faviconTs = 0
@@ -112,18 +220,35 @@ function filterHistory (history, keyword) {
terms.every(t => (h.title || '').toLowerCase().includes(t) || h.url.toLowerCase().includes(t))
)
}
+// FILETIME → 友好访问时间(与 Chrome 历史页类似):
+// 今天显示 HH:mm;今年显示 MM-DD HH:mm;更早显示 YYYY-MM-DD;异常时间戳返回空
+function formatVisitTime (ft) {
+ const ms = filetimeToMs(ft)
+ if (ms == null) return ''
+ const d = new Date(ms)
+ const now = new Date()
+ const hh = String(d.getHours()).padStart(2, '0')
+ const mm = String(d.getMinutes()).padStart(2, '0')
+ const mdd = String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
+ if (d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()) return hh + ':' + mm
+ if (d.getFullYear() === now.getFullYear()) return mdd + ' ' + hh + ':' + mm
+ return d.getFullYear() + '-' + mdd
+}
+
function historyToItem (h) {
- return { title: h.title || h.url, url: h.url, browser: h.browser, source: 'history', addAt: h.lastVisit || 0 }
+ const item = { title: h.title || h.url, url: h.url, browser: h.browser, source: 'history', addAt: h.lastVisit || 0, file: h.file }
+ item.timeText = formatVisitTime(h.lastVisit)
+ return item
}
function fallbackIcon (browser) {
- return browser === 'edge' ? 'edge.png' : 'chrome.png'
+ return browser === 'edge' ? 'icons/edge.svg' : 'icons/chrome.png'
}
-// 描述行:浏览器字母 emoji(🇨 Chrome / 🇪 Edge)+ 类型 emoji + URL
+// 描述行:初始只渲染 URL(历史记录条目访问时间跟在 URL 后),类型/浏览器图标由 decorateTypeIcons 注入(避免闪现 emoji)
function formatDescription (item) {
- const typeEmoji = item.source === 'history' ? '🕘' : '⭐'
- return typeEmoji + ' · ' + item.url
+ if (item.source === 'history' && item.timeText) return item.url + ' ' + item.timeText
+ return item.url
}
function attachFavicon (item, fmap) {
@@ -135,9 +260,14 @@ function attachFavicon (item, fmap) {
function openUrlByChrome (url) {
if (process.platform === 'win32') {
- const portableExe = getConfig().chromeExe
+ const cfg = getConfig()
+ const portableExe = cfg.chromeExe
if (portableExe && fs.existsSync(portableExe)) {
- cp.spawn(portableExe, [url], { detached: true })
+ // 与打开内部页一致:带 --user-data-dir(已做目录层级修正),确保用配置的浏览器配置打开网页
+ const args = [url]
+ const dataRoot = resolveUserDataRoot(cfg.chromeDirs && cfg.chromeDirs[0])
+ if (dataRoot) args.unshift('--user-data-dir=' + dataRoot)
+ cp.spawn(portableExe, args, { detached: true })
return
}
const suffix = `${path.sep}Google${path.sep}Chrome${path.sep}Application${path.sep}chrome.exe`
@@ -159,7 +289,8 @@ function openUrlByChrome (url) {
}
function openUrlByEdge (url) {
if (process.platform === 'win32') {
- cp.spawn('start', ['microsoft-edge:' + url], { shell: 'cmd.exe', detached: true }).once('error', () => {
+ // start 命令首参数为窗口标题(空引号占位);协议 URL 必须加引号,否则含 & 等字符会被 cmd 截断
+ cp.spawn('start', ['""', '"microsoft-edge:' + url + '"'], { shell: 'cmd.exe', detached: true }).once('error', () => {
window.ztools.shellOpenExternal(url)
})
return
@@ -171,21 +302,172 @@ function openUrlByEdge (url) {
}
}
+// 解析搜索词尾部的时间过滤指令,返回 { rest, timeFilter }
+// 支持:-t(今天 today)、-w(最近 7 天 week)、-d YYYYMMDD[-YYYYMMDD](date 区间,单日=当天)
+// 日期可不写年份:-d 0901 表示今年 9 月 1 日;跨年区间(如 0901-0101)结束日期自动视为下一年
+// 例:`xxx -t`、`chrome历史记录 -w`、`xxx -d 20260901-20261001`、`xxx -d 0901`
+function parseTimeFilter (word) {
+ const src = (word || '').trim()
+ let rest = src
+ let timeFilter = null
+ // 匹配 -t / -w / -d <4位或8位日期[可选区间];日期段也可 4位(MMDD)+4位(MMDD)
+ const m = src.match(/(^|\s)(-t|-w|-d\s+(?:\d{4}(?:-\d{4})?|\d{8}(?:-\d{8})?))(?=\s|$)/i)
+ if (m) {
+ const raw = m[2]
+ const nowY = new Date().getFullYear()
+ const fixY = (s) => s.length === 8 ? s : String(nowY) + s // 4 位 MMDD → 补今年年份
+ if (/^-t$/i.test(raw)) {
+ timeFilter = { raw, type: 'today' }
+ } else if (/^-w$/i.test(raw)) {
+ timeFilter = { raw, type: 'week' }
+ } else {
+ const dm = raw.match(/-d\s+(\d{8}|\d{4})(?:-(\d{8}|\d{4}))?/i)
+ let from = fixY(dm[1])
+ let to = fixY(dm[2] || dm[1])
+ // 跨年区间:结束日期 MMDD 小于开始日期时视为下一年(如 0901-0101 → 2026-0901 至 2027-0101)
+ if (Number(to) < Number(from)) to = String(Number(from.slice(0, 4)) + 1) + to.slice(4)
+ timeFilter = { raw, type: 'date', from, to }
+ }
+ rest = (src.slice(0, m.index) + ' ' + src.slice(m.index + m[0].length)).trim().replace(/\s+/g, ' ')
+ }
+ return { rest, timeFilter }
+}
+
+// 本地日期 → YYYYMMDD(用于区间比较)
+function ymdNum (d) {
+ return d.getFullYear() * 10000 + (d.getMonth() + 1) * 100 + d.getDate()
+}
+
+// 历史记录条目是否命中时间过滤(addAt 为 FILETIME)
+function matchTimeFilter (item, timeFilter) {
+ if (!timeFilter || !timeFilter.type) return true
+ const ms = filetimeToMs(item.addAt)
+ if (ms == null) return false
+ const d = new Date(ms)
+ const ymd = ymdNum(d)
+ if (timeFilter.type === 'today') {
+ return ymd === ymdNum(new Date())
+ }
+ if (timeFilter.type === 'week') {
+ const now = new Date()
+ // 最近 7 天(含今天,向前推 6 天)
+ const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 6)
+ return ymd >= ymdNum(start) && ymd <= ymdNum(now)
+ }
+ if (timeFilter.type === 'date') {
+ return ymd >= Number(timeFilter.from) && ymd <= Number(timeFilter.to)
+ }
+ return true
+}
+
+// 解析单个指令 token:支持任意顺序组合,如 -ch / -ed-w / -h-ed-w / -ch-t-h / -t-ch / -chb / -w / -t
+// 规则:浏览器(ch/ed)、类型(h/b)、时间(t/w)三类各自最多一个,可任意顺序连写;
+// chb/edb 为书签浏览模式(独占,不与其它组合);同类别冲突(如 -t-w、-h-b、-ch-ed)返回 null
+// 返回 null(非指令)或 { browser?, source?, browse?, time? };-d 需日期参数,由 parseTimeFilter 兜底
+function parseDirectiveToken (tok) {
+ if (!/^-/.test(tok)) return null
+ const t = tok.replace(/^-/, '').toLowerCase()
+ if (!t) return null
+ // 书签浏览模式(独占)
+ if (t === 'chb') return { browse: 'chrome' }
+ if (t === 'edb') return { browse: 'edge' }
+ // 时间片段:t/w 字符不会出现在 ch/ed/h/b 中,可直接提取;同时去掉连写分隔符 -
+ const hasT = t.includes('t')
+ const hasW = t.includes('w')
+ if (hasT && hasW) return null
+ const time = hasT ? 'today' : (hasW ? 'week' : null)
+ let s = t.replace(/[tw-]/g, '')
+ let browser = null
+ let source = null
+ // 按固定顺序消费片段;同类重复即冲突
+ if (s.includes('ed')) {
+ if (browser) return null
+ browser = 'edge'
+ s = s.replace('ed', '')
+ }
+ if (s.includes('ch')) {
+ if (browser) return null
+ browser = 'chrome'
+ s = s.replace('ch', '')
+ }
+ if (s.includes('b')) {
+ if (source) return null
+ source = 'bookmark'
+ s = s.replace('b', '')
+ }
+ if (s.includes('h')) {
+ if (source) return null
+ source = 'history'
+ s = s.replace('h', '')
+ }
+ if (s) return null
+ const d = {}
+ if (browser) d.browser = browser
+ if (source) d.source = source
+ if (time) d.time = time
+ return Object.keys(d).length ? d : null
+}
+
+// 统一指令解析:token 级剥离来源/浏览/时间指令,可在关键词前或后、可连写;
+// -d 日期参数(-d 0901 / -d 20260901-20261001)由 parseTimeFilter 兜底处理
+function parseDirectives (word) {
+ const src = (word || '').trim()
+ let browser = null
+ let source = null
+ let browse = null
+ const timeParts = []
+ const keep = []
+ for (const tok of src.split(/\s+/)) {
+ const d = parseDirectiveToken(tok)
+ if (!d) { keep.push(tok); continue }
+ if (d.browse) browse = d.browse
+ if (d.browser) browser = d.browser
+ if (d.source) source = d.source
+ if (d.time) timeParts.push(d.time)
+ }
+ const rest0 = keep.join(' ')
+ const parsed = parseTimeFilter(rest0)
+ let timeFilter = parsed.timeFilter
+ if (!timeFilter && timeParts.length) timeFilter = { raw: timeParts.join('+'), type: timeParts[0] }
+ return { rest: parsed.rest, browser, source, browse, timeFilter }
+}
+
async function searchMerged (keyword, filter) {
filter = filter || {}
- const word = (keyword || '').trim()
- ensureBookmarks()
- let books = searchBookmarks(word)
- const history = await ensureHistory()
- let hist = word ? filterHistory(history, word).map(historyToItem) : history.slice(0, 10).map(historyToItem)
+ // 统一解析:来源过滤指令(-ch / -ed / -h / -b / 组合,可连写时间)+ 时间过滤指令(-t / -w / -d)
+ const dir = parseDirectives(keyword)
+ const word = dir.rest
+ const browser = filter.browser || dir.browser || null
+ const source = filter.source || dir.source || null
+ const timeFilter = dir.timeFilter
+ // 书签与历史各自独立读取:任一侧出错不连带影响另一侧(避免书签/历史同时搜索不到)
+ let books = []
+ try {
+ ensureBookmarks()
+ // 书签类指令且未输入关键词 → 列出全部书签
+ if (source === 'bookmark' && !word) books = (getBookmarksData() || []).slice()
+ else books = searchBookmarks(word)
+ } catch (e) {}
+ let history = []
+ try { history = await ensureHistory() } catch (e) { history = [] }
+ let hist
+ if (word) {
+ hist = filterHistory(history, word).map(historyToItem)
+ } else if (timeFilter) {
+ // 有时间过滤指令时使用全量历史(否则只取少量,会导致指定日期/最近记录搜不全)
+ hist = history.map(historyToItem)
+ } else {
+ hist = history.slice(0, 100).map(historyToItem)
+ }
+ if (timeFilter) hist = hist.filter(h => matchTimeFilter(h, timeFilter))
- if (filter.browser) {
- books = books.filter(b => b.browser === filter.browser)
- hist = hist.filter(h => h.browser === filter.browser)
+ if (browser) {
+ books = books.filter(b => b.browser === browser)
+ hist = hist.filter(h => h.browser === browser)
}
let results = []
- if (!filter.source || filter.source === 'bookmark') results = results.concat(books)
- if (!filter.source || filter.source === 'history') results = results.concat(hist)
+ if (!source || source === 'bookmark') results = results.concat(books)
+ if (!source || source === 'history') results = results.concat(hist)
const fmap = faviconMap || new Map()
results = results.map(item => attachFavicon(item, fmap))
@@ -193,48 +475,1052 @@ async function searchMerged (keyword, filter) {
return results
}
+// 指令联想:仅在输入「-」(未完成输入)时显示全部指令说明。
+// 样式:一栏一条指令(上行指令、下行说明,说明前带类型标签);
+// 点击条目直接把对应指令填入输入框;末行为合并说明(note,整体弱化为描述样式)。
+function timeFilterHelp (word) {
+ const w = (word || '').trim()
+ if (w !== '-') return null
+ return [
+ { text: '-t', title: '「日期指令」今天的历史记录', directive: '-t' },
+ { text: '-w', title: '「日期指令」最近 7 天的历史记录', directive: '-w' },
+ { text: '-d', title: '「日期指令」指定日期:-d 0901 或 -d 20260901-20261001', directive: '-d ' },
+ { text: '-ch', title: '「浏览器指令」Chrome 书签 + 历史记录', directive: '-ch' },
+ { text: '-ed', title: '「浏览器指令」Edge 书签 + 历史记录', directive: '-ed' },
+ { text: '-b', title: '「类型指令」仅书签', directive: '-b' },
+ { text: '-h', title: '「类型指令」仅历史记录', directive: '-h' },
+ { text: '-chb', title: '「书签指令」Chrome 书签浏览模式(含文件夹)', directive: '-chb' },
+ { text: '-edb', title: '「书签指令」Edge 书签浏览模式(含文件夹)', directive: '-edb' },
+ { text: '不同类型指令可组合(除书签指令),书签无日期搜索,关键词与指令用空格隔开', title: '例如:-ch-t 视频(在 Chrome 今日的历史记录中搜索"视频");-ch-b-t(搜索 Chrome 的书签,-t 无效,日期只能搜索历史记录)', note: true, highlight: false }
+ ]
+}
+
+// 书签浏览模式(-chb / -edb):输入框驱动,-chb[ 路径key] 渲染对应层级
+// 路径key:browser::root(根级)或 browser::root::guid::guid...(文件夹),
+// 选择文件夹 → setSubInputValue 写入新路径触发重新渲染;返回上级同理
+// 浏览路径判断:chrome/书签栏 或 edge/其他书签 形式(区分关键词搜索)
+function isBrowsePath (browse, rest) {
+ const r = (rest || '').trim()
+ if (!r) return false
+ return /^chrome\//.test(r) || /^edge\//.test(r)
+}
+
+// 浏览模式数据:-chb / -edb 后跟 / 分隔的中文路径(如 chrome/书签栏/视频)
+// 文件夹条目带 folder 图标,书签条目带网站图标+网址+书签类型图标
+function browseBookmarksData (browse, pathKey) {
+ let tree = null
+ try { tree = (readBookmarkTree() || []).find(t => t.browser === browse) } catch (e) { tree = null }
+ const browseTok = browse === 'chrome' ? '-chb' : '-edb'
+ const browserName = browse === 'chrome' ? 'Chrome' : 'Edge'
+ if (!tree) {
+ return [{ title: '未找到 ' + browserName + ' 书签文件(请检查数据目录配置)', url: '', browser: browse, source: 'bookmark' }]
+ }
+ const items = []
+ const key = (pathKey || '').trim()
+ if (key) {
+ const upKey = parentOfBrowseKey(key)
+ items.push({ title: '返回上级', url: '', browser: browse, source: 'bookmark', upKey: browseTok + (upKey ? ' ' + upKey : ''), isUp: true, icon: svgUri(ICON_BACK.svg) })
+ }
+ let nodes = null
+ if (!key) {
+ nodes = tree.roots
+ } else {
+ const segs = key.split('/').filter(Boolean) // ['chrome','书签栏','视频']
+ const rootName = segs[1] || ''
+ const root = tree.roots.find(r => r.name === rootName)
+ if (root) {
+ nodes = root.children
+ let cur = root
+ for (let i = 2; i < segs.length; i++) {
+ const f = (cur.children || []).find(c => (c.name || '') === segs[i] && Array.isArray(c.children))
+ if (!f) { nodes = null; break }
+ cur = f
+ nodes = f.children
+ }
+ }
+ }
+ const fmap = faviconMap || new Map()
+ for (const c of (nodes || [])) {
+ if (Array.isArray(c.children)) {
+ const childKey = key ? key + '/' + (c.name || '(未命名文件夹)') : browse + '/' + (c.name || '书签栏')
+ items.push({ title: c.name || '(未命名文件夹)', url: '', browser: browse, source: 'bookmark', folderKey: browseTok + ' ' + childKey, file: tree.file, isFolder: true, icon: svgUri(ICON_FOLDER.svg) })
+ } else if (c.url) {
+ items.push(attachFavicon({ title: c.name || c.url, url: c.url, browser: browse, source: 'bookmark', file: tree.file, guid: c.guid || '' }, fmap))
+ }
+ }
+ if (!nodes) {
+ items.push({ title: '未找到该文件夹,请返回上级重试', url: '', browser: browse, source: 'bookmark', highlight: false })
+ }
+ if (!faviconMap) ensureFavicons().catch(() => {})
+ return items
+}
+
+// 浏览路径上级:chrome/书签栏/视频 → chrome/书签栏;只剩 chrome/书签栏 → 空(根级)
+function parentOfBrowseKey (key) {
+ const segs = (key || '').split('/').filter(Boolean)
+ if (segs.length <= 2) return ''
+ return segs.slice(0, -1).join('/')
+}
+
+// 浏览模式下关键词搜索:结果含文件夹(可进入)与书签(带图标/网址/类型图标)
+function searchBrowseBooks (browse, word) {
+ try { ensureBookmarks() } catch (e) {}
+ const w = (word || '').trim().toLowerCase()
+ const items = []
+ const fmap = faviconMap || new Map()
+ const browseTok = browse === 'chrome' ? '-chb' : '-edb'
+ // 1) 文件夹匹配(遍历书签树,含深层文件夹)
+ try {
+ const tree = (readBookmarkTree() || []).find(t => t.browser === browse)
+ if (tree) {
+ const walk = (nodes, parentKey) => {
+ for (const c of (nodes || [])) {
+ if (!Array.isArray(c.children)) continue
+ const childKey = parentKey ? parentKey + '/' + (c.name || '(未命名文件夹)') : browse + '/' + (c.name || '书签栏')
+ if ((c.name || '').toLowerCase().includes(w)) {
+ items.push({ title: c.name || '(未命名文件夹)', url: '', browser: browse, source: 'bookmark', folderKey: browseTok + ' ' + childKey, file: tree.file, isFolder: true, icon: svgUri(ICON_FOLDER.svg) })
+ }
+ walk(c.children, childKey)
+ }
+ }
+ walk(tree.roots, null)
+ }
+ } catch (e) {}
+ // 2) 书签匹配
+ try {
+ const books = searchBookmarks(word).filter(b => b.browser === browse)
+ for (const b of books) items.push(attachFavicon(b, fmap))
+ } catch (e) {}
+ if (!faviconMap) ensureFavicons().catch(() => {})
+ return items
+}
+
window.ztools.onMainPush(async ({ payload }) => {
+ closePickModal()
+ // 从设置页返回搜索时:移除设置页覆盖层,恢复官方列表渲染
+ removeSettingsOverlay()
const word = (payload || '').trim()
- if (!word) return { type: 'list', data: [] }
+ if (!word) {
+ currentListItems = []
+ return { type: 'list', data: [] }
+ }
+ // 输入 - / -t / -w / -d 等前缀时显示指令联想(不参与实际搜索)
+ const help = timeFilterHelp(word)
+ if (help) {
+ currentListItems = []
+ // 官方渲染为异步,下一帧弱化末行帮助说明(失败不影响列表)
+ setTimeout(() => { try { weakenHelpNote() } catch (e) {} }, 0)
+ return { type: 'list', data: help.map(x => {
+ const it = { text: x.text, title: x.title, directive: x.directive || '' }
+ if (x.highlight === false) it.highlight = false
+ return it
+ }) }
+ }
+ // 书签浏览模式:-chb / -edb [路径key 或 关键词],按文件夹逐层查看 / 搜索书签
+ const dir0 = parseDirectives(word)
+ if (dir0.browse) {
+ const items = buildBrowseData(dir0.browse, dir0.rest)
+ currentSearchCtx = { word, filter: currentSearchFilter, setList: null }
+ // 浏览模式不截断条目(文件夹层级可能较多),与插件内搜索路径一致
+ const data = items.map(x => ({
+ text: x.title,
+ title: x.description || '',
+ icon: x.icon || '',
+ browser: x.browser,
+ url: x.url || '',
+ source: x.source,
+ folderKey: x.folderKey || '',
+ upKey: x.upKey || '',
+ directive: x.directive || ''
+ }))
+ setTimeout(() => { try { decorateTypeIcons() } catch (e) {} }, 0)
+ return { type: 'list', data }
+ }
const all = await searchMerged(word, {})
+ // 全局搜索路径也要维护列表状态:右键菜单取当前条目、删除后刷新、混合搜索图标装饰
+ // (否则右键会误用上一次指令搜索的旧数据)
+ currentListItems = all
+ currentSearchFilter = {}
+ currentSearchCtx = { word, filter: {}, setList: null }
const data = all.slice(0, 6).map(x => ({
text: x.title + ' ' + x.url,
title: x.description,
icon: x.icon,
browser: x.browser,
- url: x.url
+ url: x.url,
+ source: x.source
}))
if (all.length > 6) {
data.pop()
data.push({ highlight: false, text: '共搜索到 ' + all.length + ' 条(书签+历史),查看更多...' })
}
+ // 官方渲染为异步(onMainPush 返回后渲染),下一帧再装饰图标(失败不影响列表)
+ setTimeout(() => { try { decorateTypeIcons() } catch (e) {} }, 0)
return { type: 'list', data }
}, ({ option }) => {
+ closePickModal()
+ // 指令联想:点击条目把指令填入输入框
+ if (option && option.directive) {
+ window.ztools.setSubInputValue(option.directive)
+ return
+ }
+ // 书签浏览模式:选择文件夹/返回上级 → 更新输入框路径触发重新渲染
+ if (option && option.folderKey) {
+ window.ztools.setSubInputValue(option.folderKey)
+ return
+ }
+ if (option && option.upKey) {
+ window.ztools.setSubInputValue(option.upKey)
+ return
+ }
+ if (!option || !option.url) return
if (option.browser === 'chrome') openUrlByChrome(option.url)
else openUrlByEdge(option.url)
})
+// ==================== 右键操作菜单 ====================
+let currentListItems = null // 当前渲染的搜索结果(供右键菜单取数据)
+let contextMenuEl = null
+let menuAutoCloseTimer = null // 右键菜单无操作自动关闭计时器
+
+// SVG 图标(data URI 内嵌,避免额外文件)
+const svgUri = svg => 'data:image/svg+xml;utf8,' + encodeURIComponent(svg)
+const readSvgText = name => fs.readFileSync(path.join(__dirname, 'icons', name), 'utf-8')
+// 地址栏内联图标:将固定白色描边替换为 currentColor,跟随链接文字颜色
+const inlineSvg = (name, size) => {
+ const svg = readSvgText(name)
+ .replace(/stroke="#ffffff"/gi, 'stroke="currentColor"')
+ .replace(/fill="#ffffff"/gi, 'fill="currentColor"')
+ return { svg, size }
+}
+// 地址栏内联图标:替换为指定颜色(书签黄 / 历史蓝)
+const inlineSvgColor = (name, size, color) => {
+ const svg = readSvgText(name)
+ .replace(/stroke="#ffffff"/gi, 'stroke="' + color + '"')
+ .replace(/fill="#ffffff"/gi, 'fill="' + color + '"')
+ return { svg, size }
+}
+const ICON_BOOKMARK_INLINE = inlineSvgColor('bookmark.svg', 14, '#f6a332')
+const ICON_CLOCK_INLINE = inlineSvgColor('history.svg', 14, '#77b0ff')
+const ICON_CHROME_INLINE = inlineSvg('brand-chrome.svg', 16)
+const ICON_EDGE_INLINE = inlineSvg('brand-edge.svg', 16)
+// 书签浏览模式图标:文件夹 / 返回上级(返回图标 12px,圆角 8px)
+const ICON_FOLDER = inlineSvg('folder.svg', 16)
+const ICON_BACK = inlineSvg('back.svg', 12)
+// 菜单图标(跟随字体颜色 currentColor,与附件 SVG 一一对应)
+const ICON_COMPASS = inlineSvg('compass.svg', 16)
+const ICON_HOME = inlineSvg('home.svg', 16)
+const ICON_COPY = inlineSvg('copy.svg', 16)
+const ICON_BOOKMARK_MENU = inlineSvg('bookmark.svg', 16)
+const ICON_HISTORY_MENU = inlineSvg('history.svg', 16)
+const ICON_TRASH = inlineSvg('trash.svg', 16)
+// 删除确认浮层图标(跟随 currentColor,颜色由调用处控制)
+const ICON_CHECK_SQUARE = inlineSvg('check-square.svg', 16)
+const ICON_X = inlineSvg('x.svg', 16)
+// 设置页 info 悬浮说明图标(白色描边 → currentColor,跟随主题)
+const ICON_INFO = inlineSvg('info.svg', 14)
+// 设置页「重新读取」图标(白色描边 → currentColor)
+const ICON_ROTATE = inlineSvg('rotate-right.svg', 15)
+// 设置页行内操作图标(编辑 / 删除)
+const ICON_EDIT_SETTINGS = inlineSvg('edit.svg', 15)
+const ICON_TRASH_SETTINGS = inlineSvg('trash.svg', 15)
+// 删除确认弹窗警示图标
+const ICON_ALERT = inlineSvg('alert-triangle.svg', 18)
+// 浏览器卡片右上角复制地址图标
+const ICON_COPY_ADDR = inlineSvg('cpu.svg', 16)
+
+let currentSearchFilter = null // 当前搜索的 filter(判断是否混合搜索)
+let currentSearchCtx = null // { word, filter, setList } 删除后用于刷新列表
+
+// 创建内联 SVG 元素(颜色继承 currentColor)
+// 纯字符串 + innerHTML,不依赖 DOMParser(避免真实环境解析失败导致搜索列表装饰抛异常)
+function makeInlineSvg (def) {
+ const el = document.createElement('span')
+ el.style.cssText = 'display:inline-block;width:' + def.size + 'px;height:' + def.size + 'px;vertical-align:-2px;margin-right:5px;flex-shrink:0;line-height:0;'
+ el.innerHTML = def.svg.replace(/