Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions plugins/open-chrome-tabs/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# 更新记录

## 1.0.4

- 首次提交插件市场,增加配对页的 Chrome 扩展下载入口。
- 在 ZTools 顶部搜索栏按标题和网址筛选已打开的标签页,支持鼠标和键盘切换。
- 自动刷新时保留输入,重新呼出插件后继续筛选。
- 本机配对后支持跨 Chrome 窗口搜索,结果显示网址和窗口编号。
21 changes: 21 additions & 0 deletions plugins/open-chrome-tabs/LICENSE
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions plugins/open-chrome-tabs/README.md
Original file line number Diff line number Diff line change
@@ -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)。
160 changes: 160 additions & 0 deletions plugins/open-chrome-tabs/bridge.js
Original file line number Diff line number Diff line change
@@ -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 };
23 changes: 23 additions & 0 deletions plugins/open-chrome-tabs/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'">
<title>Chrome 标签页搜索</title>
<link rel="stylesheet" href="style.css">
<script defer src="search.js"></script>
<script defer src="view.js"></script>
</head>
<body>
<div id="status" class="status" role="status">正在连接 Chrome…</div>
<section id="pairing" class="notice" hidden>
<h1>连接 Chrome</h1>
<p>首次使用时,复制配对码并粘贴到 Chrome 的「ZTools Chrome 标签页连接器」扩展中。已配对时,请确认 Chrome 和该扩展已启用。</p>
<button id="copy" type="button">复制配对码</button>
<button id="download" type="button">下载 Chrome 扩展</button>
</section>
<div id="results" role="listbox" tabindex="0" aria-label="匹配的标签页"></div>
<footer id="help" hidden><span>↑ ↓ 选择</span><span>Enter 切换</span></footer>
</body>
</html>
Binary file added plugins/open-chrome-tabs/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions plugins/open-chrome-tabs/plugin.json
Original file line number Diff line number Diff line change
@@ -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"]
}
]
}
44 changes: 44 additions & 0 deletions plugins/open-chrome-tabs/preload.js
Original file line number Diff line number Diff line change
@@ -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 });
29 changes: 29 additions & 0 deletions plugins/open-chrome-tabs/search.js
Original file line number Diff line number Diff line change
@@ -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;
})();
32 changes: 32 additions & 0 deletions plugins/open-chrome-tabs/style.css
Original file line number Diff line number Diff line change
@@ -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; }
Loading
Loading