为 Chromium 浏览器加入书签和持久历史

This commit is contained in:
xhgit committed 2026-11-13 19:20:46 +08:00
1 parent c27ad52dab
commit ae04cc9494
9 files changed
+200 -6

No files matched your search

+5 -1
View File
@@ -9,7 +9,7 @@
</head>
<body>
<header>
<div class="tabs"><div id="tabs" aria-label="标签页"></div><button data-action="new" aria-label="新建标签页">+</button><span id="mode"></span></div>
<div class="tabs"><div id="tabs" aria-label="标签页"></div><button data-action="new" aria-label="新建标签页">+</button><span id="mode"></span><button data-action="bookmark">添加书签</button><button data-action="library">书签与历史</button></div>
<form id="address-form">
<button type="button" data-action="back" aria-label="后退">←</button>
<button type="button" data-action="forward" aria-label="前进">→</button>
@@ -26,5 +26,9 @@
</form>
<div id="status" role="status"></div>
</header>
<main id="library" hidden>
<section><h1>书签</h1><ul id="bookmarks"></ul></section>
<section><h1>浏览历史</h1><ul id="history"></ul></section>
</main>
</body>
</html>
+7
View File
@@ -16,4 +16,11 @@ form { padding: 6px 8px 2px; }
input { flex: 1; min-width: 0; }
#status { padding: 0 10px; color: light-dark(#943f42,#ffb3b9); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
#mode { margin-left: auto; white-space: nowrap; }
#library { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 18px; padding: 18px; }
#library[hidden] { display: none; }
#library h1 { font-size: 18px; margin: 0 0 10px; }
#library ul { list-style: none; margin: 0; padding: 0; }
#library li { display: flex; gap: 6px; align-items: start; margin-bottom: 6px; }
#library li button:first-child { display: grid; flex: 1; text-align: left; white-space: normal; overflow-wrap: anywhere; }
#library li span { font-size: 11px; opacity: .78; }
@media (max-width: 750px) { form [data-action="zoomIn"], form [data-action="zoomOut"] { display: none; } }
+38
View File
@@ -5,6 +5,34 @@ const status = document.querySelector('#status')
const button = (action) => document.querySelector(`[data-action="${action}"]`)
let current
function renderEntries(selector, entries, removable) {
const container = document.querySelector(selector)
const rows = entries.map((entry) => {
const row = document.createElement('li')
const open = document.createElement('button')
const title = document.createElement('strong')
const url = document.createElement('span')
title.textContent = entry.title || entry.url
url.textContent = entry.url
open.append(title, url)
open.onclick = () => void command('openEntry', entry.id)
row.append(open)
if (removable) {
const remove = document.createElement('button')
remove.textContent = '移除'
remove.onclick = () => void command('removeBookmark', entry.id)
row.append(remove)
}
return row
})
if (!rows.length) {
const empty = document.createElement('li')
empty.textContent = removable ? '暂无书签' : '暂无历史记录'
rows.push(empty)
}
container.replaceChildren(...rows)
}
function render(state) {
current = state
tabs.replaceChildren(...state.tabs.map((tab) => {
@@ -28,6 +56,16 @@ function render(state) {
button('reload').setAttribute('aria-label', state.loading ? '停止加载' : '刷新')
for (const action of ['copy', 'external', 'zoomIn', 'zoomOut']) button(action).disabled = !state.url
document.querySelector('#mode').textContent = state.privateMode ? '隐私窗口' : ''
button('bookmark').hidden = state.privateMode
button('bookmark').disabled = !state.url
button('bookmark').textContent = state.bookmarked ? '取消书签' : '添加书签'
button('library').hidden = state.privateMode
button('library').setAttribute('aria-pressed', String(state.libraryMode))
document.querySelector('#library').hidden = !state.libraryMode
if (state.libraryMode) {
renderEntries('#bookmarks', state.bookmarks, true)
renderEntries('#history', state.history, false)
}
status.textContent = state.error
}
+66
View File
@@ -0,0 +1,66 @@
import { app } from 'electron'
import { randomUUID } from 'node:crypto'
import { readFileSync, renameSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
export type Entry = { id: string; url: string; title: string; time: number }
type Library = { bookmarks: Entry[]; history: Entry[] }
let cache: Library | undefined
const file = () => join(app.getPath('userData'), 'browser-library.json')
export function library(): Library {
if (cache) return cache
try {
const saved = JSON.parse(readFileSync(file(), 'utf8')) as Partial<Library>
cache = { bookmarks: parseEntries(saved.bookmarks), history: parseEntries(saved.history) }
} catch {
cache = { bookmarks: [], history: [] }
}
return cache
}
function parseEntries(value: unknown): Entry[] {
if (!Array.isArray(value)) return []
return value.slice(0, 250).filter((item): item is Entry =>
typeof item?.id === 'string' && typeof item.url === 'string' &&
typeof item.title === 'string' && typeof item.time === 'number')
}
function persist(next: Library) {
const target = file()
const temporary = target + '.tmp'
writeFileSync(temporary, JSON.stringify(next), { mode: 0o600 })
renameSync(temporary, target)
cache = next
}
function entry(url: string, title: string): Entry {
return { id: randomUUID(), url, title: title.trim().slice(0, 200), time: Date.now() }
}
export function visit(url: string, title: string) {
const previous = library()
const first = previous.history[0]
if (first?.url === url && first.title === title) return
const history = [entry(url, title), ...previous.history.filter((item) => item.url !== url)].slice(0, 250)
persist({ ...previous, history })
}
export function toggleBookmark(url: string, title: string) {
const previous = library()
const present = previous.bookmarks.some((item) => item.url === url)
if (!present && previous.bookmarks.length >= 250) throw new Error('书签数量已达上限')
const bookmarks = present ? previous.bookmarks.filter((item) => item.url !== url) :
[entry(url, title), ...previous.bookmarks]
persist({ ...previous, bookmarks })
}
export function removeBookmark(id: string) {
const previous = library()
persist({ ...previous, bookmarks: previous.bookmarks.filter((item) => item.id !== id) })
}
export function clearHistory() {
persist({ ...library(), history: [] })
}
+58 -3
View File
@@ -2,6 +2,7 @@ import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, session, shell, W
import type { Session } from 'electron'
import { randomUUID } from 'node:crypto'
import { join } from 'node:path'
import { clearHistory, library, removeBookmark, toggleBookmark, visit } from './browser-library'
const browserURL = 'xhchat://app/browser'
const height = 102
@@ -14,6 +15,7 @@ type BrowserWindowState = {
privateMode: boolean
tabs: Tab[]
active?: Tab
libraryMode: boolean
}
const windows = new Map<number, BrowserWindowState>()
@@ -39,6 +41,7 @@ function address(value: string): URL | undefined {
function state(browser: BrowserWindowState) {
const contents = browser.active?.view.webContents
const collection = browser.privateMode ? { bookmarks: [], history: [] } : library()
return {
privateMode: browser.privateMode,
active: browser.active?.id,
@@ -48,6 +51,9 @@ function state(browser: BrowserWindowState) {
forward: contents?.navigationHistory.canGoForward() ?? false,
loading: contents?.isLoading() ?? false,
error: browser.active?.error ?? '',
libraryMode: browser.libraryMode,
bookmarked: collection.bookmarks.some((item) => item.url === contents?.getURL()),
...collection,
}
}
@@ -59,6 +65,7 @@ function resize(browser: BrowserWindowState) {
const [width, total] = browser.window.getContentSize()
const top = browser.window.isFullScreen() ? 0 : height
browser.active?.view.setBounds({ x: 0, y: top, width, height: Math.max(0, total - top) })
browser.active?.view.setVisible(!browser.libraryMode)
}
function activate(browser: BrowserWindowState, tab?: Tab) {
@@ -71,6 +78,10 @@ function activate(browser: BrowserWindowState, tab?: Tab) {
update(browser)
}
function updateNormalWindows() {
for (const browser of windows.values()) if (!browser.privateMode) update(browser)
}
async function navigate(tab: Tab, url: URL) {
tab.error = ''
try {
@@ -106,11 +117,23 @@ function addTab(browser: BrowserWindowState, url?: URL) {
if (mainFrame && code !== -3) tab.error = '网页加载失败,请检查地址或网络。'
update(browser)
})
function remember() {
const current = website(contents.getURL())
if (!browser.privateMode && current && current.href.length <= 4096) {
try {
visit(current.href, contents.getTitle())
updateNormalWindows()
} catch {
tab.error = '无法保存浏览历史'
}
}
update(browser)
}
contents.on('did-navigate', () => { tab.error = ''; update(browser) })
contents.on('did-navigate-in-page', () => update(browser))
contents.on('did-navigate-in-page', (_event, _url, mainFrame) => { if (mainFrame) remember() })
contents.on('page-title-updated', () => update(browser))
contents.on('did-start-loading', () => update(browser))
contents.on('did-stop-loading', () => update(browser))
contents.on('did-stop-loading', remember)
contents.on('enter-html-full-screen', () => resize(browser))
contents.on('leave-html-full-screen', () => resize(browser))
contents.on('before-input-event', (event, input) => {
@@ -179,7 +202,7 @@ export function openBrowser(trusted: Session, privateMode = false) {
sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false,
},
})
const browser: BrowserWindowState = { window, sites, privateMode, tabs: [] }
const browser: BrowserWindowState = { window, sites, privateMode, tabs: [], libraryMode: false }
const id = window.webContents.id
windows.set(id, browser)
window.setMenuBarVisibility(false)
@@ -225,6 +248,8 @@ export function registerBrowserHandlers(trusted: Session) {
case 'go': {
const target = typeof value === 'string' ? address(value) : undefined
if (!target) throw new Error('请输入 HTTPS 地址或搜索关键词。')
browser.libraryMode = false
resize(browser)
if (tab) void navigate(tab, target)
break
}
@@ -237,6 +262,35 @@ export function registerBrowserHandlers(trusted: Session) {
case 'zoomIn': if (contents) contents.setZoomLevel(Math.min(4, contents.getZoomLevel() + 1)); break
case 'zoomOut': if (contents) contents.setZoomLevel(Math.max(-3, contents.getZoomLevel() - 1)); break
case 'fullscreen': browser.window.setFullScreen(!browser.window.isFullScreen()); break
case 'library': {
if (browser.privateMode) throw new Error('隐私窗口不记录浏览历史')
browser.libraryMode = !browser.libraryMode
resize(browser)
break
}
case 'bookmark': {
if (browser.privateMode || !current || current.href.length > 4096) throw new Error('此页面无法添加书签')
toggleBookmark(current.href, contents?.getTitle() ?? '')
updateNormalWindows()
break
}
case 'removeBookmark': {
if (browser.privateMode || typeof value !== 'string') break
removeBookmark(value)
updateNormalWindows()
break
}
case 'openEntry': {
if (browser.privateMode || typeof value !== 'string') break
const { bookmarks, history } = library()
const entry = [...bookmarks, ...history].find((item) => item.id === value)
const target = entry ? website(entry.url) : undefined
if (!target) throw new Error('该网址不可用')
browser.libraryMode = false
resize(browser)
if (tab) void navigate(tab, target)
break
}
case 'clear': {
const answer = await dialog.showMessageBox(browser.window, {
type: 'question', message: '清除浏览器 Cookie、缓存和网站数据?',
@@ -244,6 +298,7 @@ export function registerBrowserHandlers(trusted: Session) {
})
if (answer.response === 1) {
await browser.sites.clearData()
if (!browser.privateMode) clearHistory()
for (const candidate of windows.values()) {
if (candidate.sites !== browser.sites) continue
for (const tab of candidate.tabs) tab.view.webContents.navigationHistory.clear()