diff --git a/plugins/open-chrome-tabs/CHANGELOG.md b/plugins/open-chrome-tabs/CHANGELOG.md new file mode 100644 index 000000000..e9d3a618a --- /dev/null +++ b/plugins/open-chrome-tabs/CHANGELOG.md @@ -0,0 +1,8 @@ +# 更新记录 + +## 1.0.4 + +- 首次提交插件市场,增加配对页的 Chrome 扩展下载入口。 +- 在 ZTools 顶部搜索栏按标题和网址筛选已打开的标签页,支持鼠标和键盘切换。 +- 自动刷新时保留输入,重新呼出插件后继续筛选。 +- 本机配对后支持跨 Chrome 窗口搜索,结果显示网址和窗口编号。 diff --git a/plugins/open-chrome-tabs/LICENSE b/plugins/open-chrome-tabs/LICENSE new file mode 100644 index 000000000..d63343a16 --- /dev/null +++ b/plugins/open-chrome-tabs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 BeautyChaser + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/open-chrome-tabs/README.md b/plugins/open-chrome-tabs/README.md new file mode 100644 index 000000000..ede19c757 --- /dev/null +++ b/plugins/open-chrome-tabs/README.md @@ -0,0 +1,5 @@ +# Chrome 标签页搜索 + +输入 `ctab` 后按标题或网址查找当前 Chrome 标签页。列表会自动更新并保留已输入的搜索词。按回车或点击结果即可切回现有标签页。 + +首次使用需要 [下载 Chrome 连接器](https://github.com/BeautyChaser/ztools-chrome-tabs/releases/latest)。在 Chrome 的 `chrome://extensions` 加载解压后的扩展目录,然后从 ZTools 复制配对码并在 Chrome 扩展里保存。详细步骤和两个组件的源码见 [项目仓库](https://github.com/BeautyChaser/ztools-chrome-tabs)。 diff --git a/plugins/open-chrome-tabs/bridge.js b/plugins/open-chrome-tabs/bridge.js new file mode 100644 index 000000000..747675b94 --- /dev/null +++ b/plugins/open-chrome-tabs/bridge.js @@ -0,0 +1,160 @@ +const http = require('node:http'); +const { createHmac, randomUUID, timingSafeEqual } = require('node:crypto'); +const { EventEmitter } = require('node:events'); + +const HOST = '127.0.0.1'; +const PORT = 43721; +const EXTENSION_ORIGIN = 'chrome-extension://kgdnajhpcihlcaloghdoomalkmgpekcg'; +const UUID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/; +const HEX_KEY = /^[a-f0-9]{64}$/; +const POLL_TIMEOUT = 15_000; +const TASK_TIMEOUT = 2500; +const MAX_BODY = 8 * 1024 * 1024; + +function createBridge(secret, port = PORT) { + const key = Buffer.from(secret, 'hex'); + const peers = new Map(); + const pending = new Map(); + const events = new EventEmitter(); + + function sign(direction, message) { + return createHmac('sha256', key).update(`${direction}:${message}`).digest(); + } + + function finish(response, status, body) { + response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + response.end(body); + } + + function dispatch(peer) { + if (!peer.reply) return; + const task = peer.queue.shift(); + if (task) peer.reply(task.command); + } + + function receivePoll(request, response) { + const { client, challenge } = request; + if (!UUID.test(challenge)) return finish(response, 400); + for (const [id, peer] of peers) { + if (!peer.reply && !peer.queue.length && Date.now() - peer.seen > 30_000) peers.delete(id); + } + const isNew = !peers.has(client); + const peer = peers.get(client) || { queue: [] }; + peers.set(client, peer); + peer.seen = Date.now(); + peer.reply?.(null); + + const timer = setTimeout(() => peer.reply?.(null), POLL_TIMEOUT); + function clear() { + clearTimeout(timer); + if (peer.reply === reply) peer.reply = null; + peer.seen = Date.now(); + } + function reply(command) { + clear(); + const message = JSON.stringify({ challenge, command }); + finish(response, 200, JSON.stringify({ message, mac: sign('response', message).toString('hex') })); + } + peer.reply = reply; + response.once('close', clear); + dispatch(peer); + if (isNew) events.emit('peer', client); + } + + function receiveResult(request, response) { + const task = pending.get(request.id); + if (!task || task.client !== request.client) return finish(response, 409); + task.complete(request); + finish(response, 204); + } + + function readRequest(request, response) { + if (request.method !== 'POST' || request.url !== '/bridge' || + request.headers.host !== `${HOST}:${server.address().port}` || + request.headers.origin !== EXTENSION_ORIGIN) { + request.resume(); + return finish(response, 403); + } + + const parts = []; + let bytes = 0; + request.on('data', part => { + bytes += part.length; + if (bytes > MAX_BODY) request.destroy(); + else parts.push(part); + }); + request.on('error', () => response.destroy()); + request.on('end', () => { + let payload; + try { + const { message, mac } = JSON.parse(Buffer.concat(parts).toString('utf8')); + if (typeof message !== 'string' || typeof mac !== 'string' || !HEX_KEY.test(mac) || + !timingSafeEqual(sign('request', message), Buffer.from(mac, 'hex'))) { + return finish(response, 401); + } + payload = JSON.parse(message); + if (typeof payload?.client !== 'string' || !UUID.test(payload.client)) return finish(response, 400); + } catch { + return finish(response, 400); + } + if (payload.kind === 'next') return receivePoll(payload, response); + if (payload.kind === 'result') return receiveResult(payload, response); + finish(response, 400); + }); + } + + const server = http.createServer({ requestTimeout: 25_000, headersTimeout: 4000 }, readRequest); + server.maxConnections = 48; + server.setTimeout(22_000, socket => socket.destroy()); + const ready = new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(port, HOST, () => resolve(server.address())); + }); + + function send(client, command) { + const peer = peers.get(client); + if (!peer || Date.now() - peer.seen > 20_000) return Promise.resolve(null); + command = { id: randomUUID(), ...command }; + return new Promise(resolve => { + const timer = setTimeout(() => task.complete(null), TASK_TIMEOUT); + const task = { + client, command, + complete(result) { + clearTimeout(timer); + pending.delete(command.id); + const index = peer.queue.indexOf(task); + if (index !== -1) peer.queue.splice(index, 1); + resolve(result); + }, + }; + peer.queue.push(task); + pending.set(command.id, task); + dispatch(peer); + }); + } + + return { + ready, events, + async listTabs() { + const clients = [...peers.keys()].filter(id => Date.now() - peers.get(id).seen < 20_000); + const reports = await Promise.all(clients.map(id => send(id, { action: 'list' }))); + const live = reports.filter(report => report?.ok && Array.isArray(report.tabs)); + const tabs = live.flatMap(({ tabs, client }) => tabs.filter(tab => + Number.isInteger(tab?.id) && Number.isInteger(tab.windowId) && + typeof tab.title === 'string' && typeof tab.url === 'string' + ).map(tab => ({ ...tab, client }))); + return { connected: live.length > 0, tabs, incomplete: live.length > 0 && live.length !== clients.length }; + }, + async activate(client, tabId, url) { + const result = await send(client, { action: 'activate', tabId, url }); + return { ok: result?.ok === true, reason: result?.reason || 'offline' }; + }, + close() { + for (const task of pending.values()) task.complete(null); + server.close(); + server.closeAllConnections(); + }, + }; +} + +module.exports = { createBridge, HEX_KEY }; diff --git a/plugins/open-chrome-tabs/index.html b/plugins/open-chrome-tabs/index.html new file mode 100644 index 000000000..0b1a8c3d3 --- /dev/null +++ b/plugins/open-chrome-tabs/index.html @@ -0,0 +1,23 @@ + + + + + + + Chrome 标签页搜索 + + + + + +
正在连接 Chrome…
+ +
+ + + diff --git a/plugins/open-chrome-tabs/logo.png b/plugins/open-chrome-tabs/logo.png new file mode 100644 index 000000000..19f466107 Binary files /dev/null and b/plugins/open-chrome-tabs/logo.png differ diff --git a/plugins/open-chrome-tabs/plugin.json b/plugins/open-chrome-tabs/plugin.json new file mode 100644 index 000000000..6d176cf74 --- /dev/null +++ b/plugins/open-chrome-tabs/plugin.json @@ -0,0 +1,18 @@ +{ + "name": "open-chrome-tabs", + "title": "Chrome 标签页搜索", + "description": "按标题或网址搜索并切回已打开的 Chrome 标签页。首次使用需配对 Chrome 扩展。", + "version": "1.0.4", + "author": "BeautyChaser", + "platform": ["win32"], + "main": "index.html", + "preload": "preload.js", + "logo": "logo.png", + "features": [ + { + "code": "search-chrome-tabs", + "explain": "搜索并切换到已打开的 Chrome 标签页", + "cmds": ["Chrome 标签页", "搜标签页", "chrome tabs", "ctab"] + } + ] +} diff --git a/plugins/open-chrome-tabs/preload.js b/plugins/open-chrome-tabs/preload.js new file mode 100644 index 000000000..5313631a7 --- /dev/null +++ b/plugins/open-chrome-tabs/preload.js @@ -0,0 +1,44 @@ +const { randomBytes } = require('node:crypto'); +const { createBridge, HEX_KEY } = require('./bridge.js'); + +const STORAGE_KEY = 'chrome-tab-connector-secret'; +let bridge; + +async function service() { + if (!bridge) { + let secret = window.ztools.dbStorage.getItem(STORAGE_KEY); + if (!HEX_KEY.test(secret)) { + secret = randomBytes(32).toString('hex'); + window.ztools.dbStorage.setItem(STORAGE_KEY, secret); + } + const current = createBridge(secret); + bridge = current; + try { + await current.ready; + } catch (error) { + if (bridge === current) bridge = null; + throw error; + } + } + await bridge.ready; + return bridge; +} + +window.chromeTabConnector = { + async list() { + try { + return await (await service()).listTabs(); + } catch (error) { + return { connected: false, tabs: [], error: error.code === 'EADDRINUSE' ? 'port' : 'bridge' }; + } + }, + async activate(client, id, url) { + return (await service()).activate(client, id, url); + }, + copyPairingCode() { + const secret = window.ztools.dbStorage.getItem(STORAGE_KEY); + return HEX_KEY.test(secret) && window.ztools.copyText(secret); + }, +}; + +window.addEventListener('unload', () => bridge?.close(), { once: true }); diff --git a/plugins/open-chrome-tabs/search.js b/plugins/open-chrome-tabs/search.js new file mode 100644 index 000000000..82b760d6b --- /dev/null +++ b/plugins/open-chrome-tabs/search.js @@ -0,0 +1,29 @@ +(function () { + function fold(text) { + return text.normalize('NFKC').toLowerCase(); + } + + function decodedUrl(url) { + try { return decodeURI(url); } catch { return url; } + } + + function searchTabs(tabs, query) { + const text = fold(query).trim(); + const terms = text.split(/\s+/u).filter(Boolean); + const matches = []; + for (const tab of tabs) { + const title = fold(tab.title); + const url = fold(tab.url); + const decoded = fold(decodedUrl(tab.url)); + if (!terms.every(term => title.includes(term) || url.includes(term) || decoded.includes(term))) continue; + const exact = text && (title === text || url === text || decoded === text); + const score = exact ? 3 : title.startsWith(text) ? 2 : title.includes(text) ? 1 : 0; + matches.push({ tab, score }); + } + return matches.sort((a, b) => b.score - a.score || (b.tab.lastAccessed || 0) - (a.tab.lastAccessed || 0)) + .map(match => match.tab); + } + + if (typeof module === 'object') module.exports = { searchTabs }; + if (typeof window === 'object') window.searchChromeTabs = searchTabs; +})(); diff --git a/plugins/open-chrome-tabs/style.css b/plugins/open-chrome-tabs/style.css new file mode 100644 index 000000000..cb31b9f15 --- /dev/null +++ b/plugins/open-chrome-tabs/style.css @@ -0,0 +1,32 @@ +:root { + color-scheme: light dark; + color: light-dark(#172332, #e7edf5); + background: light-dark(#f8fafc, #171e29); + --panel: light-dark(#ffffff, #212b39); + --outline: light-dark(#dbe3ed, #39495d); + --muted: light-dark(#516276, #acb9ca); + --accent: light-dark(#214d91, #a9cbff); + --selected: light-dark(#e9f1ff, #283d5b); + font: 14px/1.45 "Segoe UI", "Microsoft YaHei", system-ui, sans-serif; +} + +* { box-sizing: border-box; } +[hidden] { display: none !important; } +body { margin: 0; height: 100dvh; display: flex; flex-direction: column; } +.status { padding: 8px 14px; color: var(--muted); font-size: 12px; } +button { font: inherit; } +button:not(.row) { padding: 6px 11px; border: 1px solid var(--outline); border-radius: 8px; background: var(--panel); color: inherit; cursor: pointer; } +button:not(.row):hover { background: var(--selected); } +:is(button, #results):focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.notice { margin: 10px 14px; padding: 15px; border: 1px solid var(--outline); border-radius: 10px; background: var(--panel); } +.notice h1 { font-size: 16px; margin: 0 0 6px; } +.notice p { color: var(--muted); margin: 0 0 12px; max-width: 55ch; } +#results { flex: 1; min-height: 0; overflow-y: auto; padding: 0 10px; } +.row { display: flex; align-items: center; gap: 12px; width: 100%; padding: 8px 10px; text-align: start; border: 1px solid transparent; border-radius: 8px; background: transparent; color: inherit; cursor: pointer; } +.row[aria-selected="true"] { border-color: var(--outline); background: var(--selected); } +.row-main { flex: 1; min-width: 0; } +.title, .url { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.title { font-weight: 600; } +.url, .window-number { font-size: 12px; color: var(--muted); } +.window-number { white-space: nowrap; } +footer { display: flex; gap: 16px; justify-content: flex-end; border-top: 1px solid var(--outline); padding: 7px 15px; color: var(--muted); font-size: 12px; } diff --git a/plugins/open-chrome-tabs/view.js b/plugins/open-chrome-tabs/view.js new file mode 100644 index 000000000..e476820bd --- /dev/null +++ b/plugins/open-chrome-tabs/view.js @@ -0,0 +1,209 @@ +const host = window.ztools; +const connector = window.chromeTabConnector; +const results = document.querySelector('#results'); +const statusLine = document.querySelector('#status'); +const pairing = document.querySelector('#pairing'); +const help = document.querySelector('#help'); +const copy = document.querySelector('#copy'); +const connectorRelease = 'https://github.com/BeautyChaser/ztools-chrome-tabs/releases/latest'; + +let session = null; +let query = ''; +let tabs = []; +let matches = []; +let activeIndex = 0; +let snapshot = ''; +let connected = false; +let incomplete = false; +let notice = ''; + +function tabKey(tab) { + return tab && `${tab.client}/${tab.id}`; +} + +function status(message) { + const text = notice || message; + if (statusLine.textContent !== text) statusLine.textContent = text; +} + +function renderStatus() { + if (!connected) return; + let message = 'Chrome 当前没有打开的标签页'; + if (tabs.length) { + message = matches.length ? `${matches.length} 个标签页` : '没有匹配的标签页'; + if (incomplete) message += ' · 部分 Chrome 配置暂时未响应'; + } + status(message); +} + +function select(index, scroll = false) { + const previous = results.children[activeIndex]; + activeIndex = index; + const next = results.children[index]; + if (previous && previous !== next) previous.setAttribute('aria-selected', 'false'); + if (!next) { + results.removeAttribute('aria-activedescendant'); + return; + } + next.setAttribute('aria-selected', 'true'); + results.setAttribute('aria-activedescendant', next.id); + if (scroll) next.scrollIntoView({ block: 'nearest' }); +} + +function render(preserveSelection = false) { + const selectedKey = preserveSelection ? tabKey(matches[activeIndex]) : null; + matches = window.searchChromeTabs(tabs, query); + const windows = [...new Set(tabs.map(tab => `${tab.client}/${tab.windowId}`))].sort(); + const windowNumbers = new Map(windows.map((key, index) => [key, index + 1])); + const rows = matches.map((tab, index) => { + const row = document.createElement('button'); + row.type = 'button'; + row.className = 'row'; + row.id = `result-${index}`; + row.tabIndex = -1; + row.setAttribute('role', 'option'); + row.setAttribute('aria-selected', 'false'); + const main = document.createElement('span'); + main.className = 'row-main'; + const title = document.createElement('span'); + title.className = 'title'; + title.textContent = tab.title || '无标题'; + const url = document.createElement('span'); + url.className = 'url'; + url.textContent = tab.url || '正在加载地址'; + main.append(title, url); + const windowNumber = document.createElement('span'); + windowNumber.className = 'window-number'; + windowNumber.textContent = `窗口 ${windowNumbers.get(`${tab.client}/${tab.windowId}`)}`; + row.title = [title.textContent, tab.url, windowNumber.textContent].filter(Boolean).join('\n'); + row.append(main, windowNumber); + row.addEventListener('pointermove', () => select(index), { passive: true }); + row.addEventListener('click', () => activate(tab)); + return row; + }); + results.replaceChildren(...rows); + if (!selectedKey) results.scrollTop = 0; + help.hidden = !matches.length; + select(Math.max(0, matches.findIndex(tab => tabKey(tab) === selectedKey)), preserveSelection); + renderStatus(); +} + +async function refresh() { + const current = session; + if (!current || current.refreshing || current.switching) return; + current.refreshing = true; + try { + const data = await connector.list(); + if (session !== current) return; + const nextSnapshot = JSON.stringify(data.tabs); + const same = snapshot === nextSnapshot && connected === data.connected; + if (data.connected && !connected) notice = ''; + connected = data.connected; + incomplete = data.incomplete; + pairing.hidden = connected || Boolean(data.error); + if (!connected) { + status(data.error === 'port' ? '连接端口 43721 已被占用。释放端口后会自动重试。' : + data.error ? '本机连接启动失败,正在自动重试。' : '等待 Chrome 连接'); + } + if (!same) { + tabs = data.tabs; + snapshot = nextSnapshot; + render(true); + } else { + renderStatus(); + } + } finally { + current.refreshing = false; + } +} + +async function activate(tab) { + const current = session; + if (!tab || !current || current.switching) return; + current.switching = true; + notice = ''; + let result; + try { + result = await connector.activate(tab.client, tab.id, tab.url); + } catch { + result = { ok: false }; + } finally { + current.switching = false; + } + if (session !== current) return; + if (result.ok) { + // ZTools can reopen this same view without a new PluginEnter event. + void refresh(); + await host.hideMainWindow(false); + return; + } + notice = result.reason === 'stale' ? '该标签页已关闭或地址已变化,正在刷新。' : '切换失败。确认 Chrome 正在运行后重试。'; + status(''); + host.subInputFocus?.(); + void refresh(); +} + +function stop() { + if (!session) return; + clearInterval(session.timer); + session = null; + tabs = []; + snapshot = ''; + matches = []; + connected = false; + notice = ''; + pairing.hidden = true; + render(); + status('正在连接 Chrome…'); +} + +function updateQuery(details) { + if (!session) return; + const text = typeof details === 'string' ? details : details?.text ?? ''; + if (query === text) return; + query = text; + notice = ''; + render(); +} + +function start() { + if (!connector || !host?.setSubInput) return status('请从 ZTools 打开这个插件。'); + if (!session) { + session = { timer: setInterval(refresh, 1600) }; + status('正在连接 Chrome…'); + host.setExpendHeight?.(445); + host.setSubInput(updateQuery, '搜索标签页标题或网址', true); + if (query) host.setSubInputValue?.(query); + } + void refresh(); +} + +document.addEventListener('keydown', event => { + if (event.isComposing || event.keyCode === 229 || !matches.length) return; + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + event.preventDefault(); + event.stopPropagation(); + const offset = event.key === 'ArrowDown' ? 1 : -1; + select(Math.max(0, Math.min(matches.length - 1, activeIndex + offset)), true); + } else if (event.key === 'Enter' && !event.target.closest?.('button')) { + event.preventDefault(); + event.stopPropagation(); + void activate(matches[activeIndex]); + } +}); + +copy.addEventListener('click', () => { + notice = connector.copyPairingCode() ? '已复制配对码,请粘贴到 Chrome 扩展中。' : '配对码尚未就绪,请稍后重试。'; + status(''); +}); +document.querySelector('#download').addEventListener('click', () => { + host.shellOpenExternal(connectorRelease); +}); + +host?.onPluginEnter?.(start); +host?.onPluginOut?.(stop); +document.addEventListener('visibilitychange', () => { + if (!document.hidden) void refresh(); +}); +window.addEventListener('focus', () => { void refresh(); }); +if (!document.hidden) start();