// ==UserScript== // @name 键盘浏览 // @name:zh-CN 键盘浏览 // @name:en Keyboard Nav — Vimium-style Keyboard Browsing // @namespace https://github.com/yilecoding/helper-scripts // @version 2025.09.22.11 // @description Vimium 风格的轻量键盘浏览:j/k、d/u、h/l、gg/G 平滑滚动(自动找到真正在滚的区域,长按连续不卡,支持 5j 数字前缀);f/F 链接提示(当前页 / 新标签打开,能提示到 open shadow DOM 里的按钮,最短无冲突标签,被遮挡的不出提示,输入框聚焦、其余派发真实点击);H/L 后退前进、r 刷新、yy 复制网址、gi 聚焦输入框。不打扰:焦点在输入框里、带 Ctrl/Alt/Meta 的组合键一律不拦,Gmail、在线文档等自带快捷键的站点默认停用(菜单按站点切换),i 进入直通模式把按键临时交给页面。? 显示全部快捷键。 // @description:zh-CN Vimium 风格的轻量键盘浏览:j/k、d/u、h/l、gg/G 平滑滚动(自动找到真正在滚的区域,长按连续不卡,支持 5j 数字前缀);f/F 链接提示(当前页 / 新标签打开,能提示到 open shadow DOM 里的按钮,最短无冲突标签,被遮挡的不出提示,输入框聚焦、其余派发真实点击);H/L 后退前进、r 刷新、yy 复制网址、gi 聚焦输入框。不打扰:焦点在输入框里、带 Ctrl/Alt/Meta 的组合键一律不拦,Gmail、在线文档等自带快捷键的站点默认停用(菜单按站点切换),i 进入直通模式把按键临时交给页面。? 显示全部快捷键。 // @description:en Lightweight Vimium-style keyboard browsing: smooth j/k, d/u, h/l and gg/G scrolling that finds the area that actually scrolls (stutter-free while a key is held, count prefixes like 5j); f/F show link hints (open in place or in a new tab, reaching into open shadow DOM, shortest prefix-free labels, covered elements skipped, inputs get focus, everything else gets a real click sequence); H/L back/forward, r reload, yy copy URL, gi focus the first input. Stays out of the way: keys typed into inputs and Ctrl/Alt/Meta combos are never intercepted, sites with their own shortcuts (Gmail, online docs) are off by default (toggle per site from the menu), and i enters pass-through mode. Press ? for the full key list. // @author 壹樂(V:ita1125) // @match http://*/* // @match https://*/* // @noframes // @grant GM_openInTab // @grant GM_setClipboard // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @license MIT // @run-at document-start // @homepageURL https://github.com/yile2020/helper-scripts // @supportURL https://github.com/yile2020/helper-scripts/issues // @updateURL https://raw.githubusercontent.com/yile2020/helper-scripts/main/keyboard-nav/keyboard-nav.user.js // @downloadURL https://raw.githubusercontent.com/yile2020/helper-scripts/main/keyboard-nav/keyboard-nav.user.js // ==/UserScript== // 脚本持续更新维护,欢迎 star / watch 仓库获取最新版本: // https://github.com/yile2020/helper-scripts (function () { 'use strict'; /** 日志前缀。控制台过滤框输入「键盘浏览」只看本脚本。 */ const TAG = '[键盘浏览]'; // ========================================================================= // 配置 // ========================================================================= const CONFIG = { scrollStep: 60, // j/k 一下滚多少像素 sequenceTimeout: 1500, // 多键序列(gg、yy)和数字前缀,两键之间最多等这么久 maxCount: 999, // 数字前缀上限,手滑按出 99999j 也不至于卡死 smooth: true, // 平滑滚动(系统开了「减少动态效果」时自动关) smoothFactor: 0.25, // 平滑滚动每 16.7ms 追上剩余距离的这么多比例 hintChars: 'sadfjklewcmpgh', // 链接提示标签用的字母,靠前的更常用 escBlurs: true, // 焦点在输入框里时 Esc 让它失焦,回到快捷键状态 // 自带整套快捷键的站点默认不启用(含子域名);菜单里可以按站点改 blockedSites: [ 'mail.google.com', 'docs.google.com', 'outlook.live.com', 'outlook.office.com', 'outlook.office365.com', 'notion.so', 'figma.com', 'docs.qq.com', 'yuque.com', 'feishu.cn', 'larksuite.com', 'shimo.im', 'kdocs.cn', ], }; // ========================================================================= // 站点开关(GM 存储) // ========================================================================= /** * 只存「和默认不一样」的站点:sites[host] = 'on' | 'off'。 * 切回默认状态时删掉这条,这样以后默认黑名单增删站点,没手动改过的站点能跟着变。 */ const Sites = (() => { const host = location.hostname; const blockedByDefault = CONFIG.blockedSites.some((d) => host === d || host.endsWith('.' + d)); function enabled() { const v = GM_getValue('sites', {})[host]; return v ? v === 'on' : !blockedByDefault; } function toggle() { const sites = GM_getValue('sites', {}); const next = !enabled(); if (next === !blockedByDefault) delete sites[host]; else sites[host] = next ? 'on' : 'off'; GM_setValue('sites', sites); return next; } return { host, enabled, toggle }; })(); // ========================================================================= // 焦点判断 // ========================================================================= /** 这些 input 不接收文字输入,焦点在上面时照样响应快捷键。 */ const NON_TEXT_INPUTS = new Set([ 'button', 'checkbox', 'radio', 'submit', 'reset', 'image', 'file', 'range', 'color', 'hidden', ]); /** 真正的焦点元素:document.activeElement 停在 shadow host 上,要钻进 shadowRoot 找。 */ function deepActiveElement() { let el = document.activeElement; while (el && el.shadowRoot && el.shadowRoot.activeElement) el = el.shadowRoot.activeElement; return el; } function isEditable(el) { if (!el || el.nodeType !== 1) return false; if (el.isContentEditable) return true; const tag = el.tagName; if (tag === 'TEXTAREA' || tag === 'SELECT') return true; if (tag === 'INPUT') return !NON_TEXT_INPUTS.has((el.getAttribute('type') || '').toLowerCase()); return false; } // ========================================================================= // 滚动 // ========================================================================= /** * 滚动目标 = 「当前可滚动的主区域」。很多站点(后台、文档站、聊天应用)body 不滚, * 滚的是内部某个 div,对 window 滚动毫无反应。 * * 选法和浏览器方向键一致:最近点击过的元素往上找第一个还能往这个方向滚的容器; * 没点过(或点的地方滚不动)就从视口中央的元素往上找,取可见面积最大的那个。 */ const Scroll = (() => { let activated = null; // 最近一次鼠标按下的元素 const root = () => document.scrollingElement || document.documentElement; const prop = (axis) => (axis === 'y' ? 'overflowY' : 'overflowX'); function rootScrollable(axis) { const r = root(); const room = axis === 'y' ? r.scrollHeight - r.clientHeight : r.scrollWidth - r.clientWidth; if (room < 1) return false; // body 的 overflow 只有 html 是 visible 时才会传给视口:body{overflow:hidden} 也能锁住整页 const html = getComputedStyle(document.documentElement)[prop(axis)]; if (html === 'hidden' || html === 'clip') return false; if (html === 'visible' && document.body) { const body = getComputedStyle(document.body)[prop(axis)]; if (body === 'hidden' || body === 'clip') return false; } return true; } function scrollable(el, axis) { if (el === root()) return rootScrollable(axis); // html 是 visible 时 body 的 overflow 已经传给了视口,body 本身不是滚动容器(设它的 scrollTop 没用); // 只有 html 自己设了 overflow(常见于 html, body { height: 100% } 的写法)body 才是独立的滚动容器 if (el === document.body && getComputedStyle(document.documentElement)[prop(axis)] === 'visible') return false; const room = axis === 'y' ? el.scrollHeight - el.clientHeight : el.scrollWidth - el.clientWidth; if (room < 1) return false; const v = getComputedStyle(el)[prop(axis)]; return v === 'auto' || v === 'scroll' || v === 'overlay'; } function pos(el, axis) { if (el === root()) return axis === 'y' ? window.scrollY : window.scrollX; return axis === 'y' ? el.scrollTop : el.scrollLeft; } function maxPos(el, axis) { return axis === 'y' ? el.scrollHeight - el.clientHeight : el.scrollWidth - el.clientWidth; } function canMove(el, axis, dir) { const p = pos(el, axis); return dir < 0 ? p > 0 : p < maxPos(el, axis) - 1; } /** 视口里能看到的面积:比 scrollHeight 更接近「哪块是主区域」。 */ function visibleArea(el) { if (el === root()) return window.innerWidth * window.innerHeight; const r = el.getBoundingClientRect(); const w = Math.min(r.right, window.innerWidth) - Math.max(r.left, 0); const h = Math.min(r.bottom, window.innerHeight) - Math.max(r.top, 0); return w > 0 && h > 0 ? w * h : 0; } /** 父元素,穿过 shadow root 到 host。 */ function parentOf(el) { if (el.parentElement) return el.parentElement; const r = el.getRootNode && el.getRootNode(); return r && r.host ? r.host : null; } function ancestors(el, axis) { const out = []; for (let n = el; n; n = parentOf(n)) { if (n === document.documentElement || n === root()) continue; if (scrollable(n, axis)) out.push(n); } if (rootScrollable(axis)) out.push(root()); return out; } /** 视口中央的元素,钻进 open shadow root 找到最深的那个。 */ function centerElement() { const x = window.innerWidth / 2; const y = window.innerHeight / 2; let el = document.elementFromPoint(x, y); while (el && el.shadowRoot) { const inner = el.shadowRoot.elementFromPoint(x, y); if (!inner || inner === el) break; el = inner; } return el; } function target(axis, dir) { if (activated && activated.isConnected) { const list = ancestors(activated, axis); const hit = list.find((el) => canMove(el, axis, dir)); if (hit) return hit; } const center = centerElement(); let list = center ? ancestors(center, axis) : []; if (!list.length) list = rootScrollable(axis) ? [root()] : scanAll(axis); if (!list.length) return null; const movable = list.filter((el) => canMove(el, axis, dir)); const pool = movable.length ? movable : list; return pool.reduce((a, b) => (visibleArea(b) > visibleArea(a) ? b : a)); } /** 兜底:视口中央压着的是一层不滚的遮罩之类,全页找可见面积最大的滚动容器。 */ function scanAll(axis) { let best = null; let bestArea = 0; for (const el of document.querySelectorAll('body *')) { const area = visibleArea(el); if (area > bestArea && scrollable(el, axis)) { best = el; bestArea = area; } } return best ? [best] : []; } function setPos(el, axis, v) { // 'instant' 而不是 'auto':页面 CSS 写了 scroll-behavior: smooth 时 'auto' 也会变成平滑滚动 const opt = { [axis === 'y' ? 'top' : 'left']: v, behavior: 'instant' }; if (el === root()) window.scrollTo(opt); else el.scrollTo(opt); } // --------------------------------------------------------------------- // 平滑滚动 // // 不用 scrollBy({ behavior: 'smooth' }):动画途中再调一次,原生实现从「当前位置」重新算, // 实测停在 60 时快速连按两下 j,最后停在 120 而不是 180;长按时每个重复 keydown 都把动画打断重来,一顿一顿。 // 这里给每个(容器, 方向)记一个目标位置,新按键只往目标上累加,rAF 每帧追剩余距离的一部分 —— // 长按时目标匀速前移、动画一直追着跑,就是连续的匀速滚动。 // --------------------------------------------------------------------- const anims = []; // { el, axis, target, last } let raf = 0; let lastFrame = 0; const reduceMotion = window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : null; const animOf = (el, axis) => anims.find((a) => a.el === el && a.axis === axis); function animateTo(el, axis, target) { if (!CONFIG.smooth || (reduceMotion && reduceMotion.matches)) { setPos(el, axis, target); return; } let a = animOf(el, axis); if (!a) anims.push((a = { el, axis, target, last: null })); a.target = target; if (!raf) { lastFrame = performance.now(); raf = requestAnimationFrame(frame); } } function frame(now) { // 按时间算比例:120Hz 屏上每帧追得少一点,整体速度和 60Hz 一样 const dt = Math.min(Math.max(now - lastFrame, 1), 100); lastFrame = now; const k = 1 - Math.pow(1 - CONFIG.smoothFactor, dt / 16.7); for (let i = anims.length - 1; i >= 0; i--) { const a = anims[i]; const cur = pos(a.el, a.axis); // 动画途中用户自己滚了(滚轮、拖滚动条):让给用户,不往回拽 const hijacked = a.last !== null && Math.abs(cur - a.last) > 2; const diff = a.target - cur; if (hijacked || !a.el.isConnected || Math.abs(diff) < 1) { if (!hijacked && a.el.isConnected) setPos(a.el, a.axis, a.target); anims.splice(i, 1); continue; } const move = Math.abs(diff * k) < 1 ? Math.sign(diff) : diff * k; setPos(a.el, a.axis, cur + move); a.last = pos(a.el, a.axis); // 设了没动(内容在动画途中变短了之类):别空转 if (a.last === cur) anims.splice(i, 1); } raf = anims.length ? requestAnimationFrame(frame) : 0; } /** 动画中的目标位置优先:连按时在上一次的目标上累加,而不是在半路的当前位置上。 */ function basePos(el, axis) { const a = animOf(el, axis); return a ? a.target : pos(el, axis); } const clamp = (el, axis, v) => Math.max(0, Math.min(maxPos(el, axis), v)); /** 滚到某一端:pos 为 0 是开头,Infinity 是末尾。 */ function to(axis, p) { const el = target(axis, p === 0 ? -1 : 1); if (el) animateTo(el, axis, clamp(el, axis, p)); } /** * delta 可以是函数:拿到滚动容器后再算(半屏要知道容器多高)。 * 这时方向要单独传 —— 选容器时要的是「还能往这个方向滚」的那个,方向错了 u 会选中一个只能往下滚的容器。 */ function by(axis, delta, dir) { const el = target(axis, dir || Math.sign(delta) || 1); if (!el) return; const d = typeof delta === 'function' ? delta(el) : delta; animateTo(el, axis, clamp(el, axis, basePos(el, axis) + d)); } /** 半屏:按容器自己的可视高度算,不是窗口高度。 */ function viewSize(el, axis) { if (el === root()) return axis === 'y' ? window.innerHeight : window.innerWidth; return axis === 'y' ? el.clientHeight : el.clientWidth; } window.addEventListener('mousedown', (e) => { activated = (e.composedPath && e.composedPath()[0]) || e.target; }, true); return { by, to, viewSize }; })(); // ========================================================================= // 界面:脚本自己的浮层都放在 shadow DOM 里,页面样式进不来、我们的样式也漏不出去 // ========================================================================= const UI_ATTR = 'data-kbnav-ui'; function createLayer(id, css) { const host = document.createElement('div'); host.id = id; host.setAttribute(UI_ATTR, ''); host.style.cssText = 'all: initial; position: fixed; inset: 0; z-index: 2147483647; pointer-events: none;'; const root = host.attachShadow({ mode: 'open' }); const style = document.createElement('style'); style.textContent = css; root.appendChild(style); (document.body || document.documentElement).appendChild(host); return root; } /** * 右下角状态区:上面是一闪而过的提示(「已复制」),下面是模式指示(直通 / 链接提示 / 已按下的前缀键)。 * 平时什么都不显示 —— 普通模式不需要提醒。 */ const Status = (() => { let root = null; let timer = 0; const CSS = ` .wrap { position: fixed; right: 16px; bottom: 16px; display: flex; flex-direction: column; align-items: flex-end; gap: 6px; font: 13px/1.5 system-ui, sans-serif; } .toast, .mode { max-width: 60vw; padding: 4px 10px; border-radius: 6px; box-shadow: 0 2px 8px rgba(0, 0, 0, .3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .toast { background: rgba(32, 33, 36, .92); color: #fff; } .mode { background: #fff7c4; color: #302505; border: 1px solid #c38a22; opacity: .92; } [hidden] { display: none; } `; function ensure() { if (root && root.host.isConnected) return root; root = createLayer('kbnav-status', CSS); const wrap = document.createElement('div'); wrap.className = 'wrap'; wrap.innerHTML = '
'; root.appendChild(wrap); return root; } function toast(text, ms = 2000) { const el = ensure().querySelector('.toast'); el.textContent = text; el.hidden = false; clearTimeout(timer); timer = setTimeout(() => { el.hidden = true; }, ms); } function mode(text) { // 不需要显示时也别为了「隐藏」去创建浮层 if (!text && !root) return; const el = ensure().querySelector('.mode'); el.textContent = text || ''; el.hidden = !text; } return { toast, mode }; })(); // ========================================================================= // 链接提示 // ========================================================================= /** * 最短、互不为前缀的标签:把字母表当成一棵树,每次把最浅的叶子展开成下一层, * 直到叶子数够用。展开过的节点不再当标签,所以任何标签都不是另一个的前缀 —— * 输完一个标签就能立刻触发,不用等超时。 */ function hintLabels(n, chars) { if (n <= 0) return []; const queue = ['']; let head = 0; while (queue.length - head < n || queue.length === 1) { const p = queue[head++]; for (const c of chars) queue.push(p + c); } return queue.slice(head, head + n); } const Hints = (() => { const CLICKABLE = [ 'a[href]', 'area[href]', 'button', 'input:not([type=hidden])', 'select', 'textarea', 'summary', 'label', '[role=button]', '[role=link]', '[role=checkbox]', '[role=radio]', '[role=switch]', '[role=tab]', '[role=menuitem]', '[role=option]', '[onclick]', '[contenteditable=""]', '[contenteditable=true]', // tabindex=-1 是框架给容器打的「可编程聚焦」标记(整块正文、弹窗外壳),不是可点击的东西 '[tabindex]:not([tabindex^="-"])', ].join(','); const CSS = ` .hint { position: fixed; padding: 1px 4px; border-radius: 3px; font: bold 12px/1.2 ui-monospace, Menlo, Consolas, monospace; letter-spacing: .5px; text-transform: uppercase; color: #302505; white-space: nowrap; background: linear-gradient(#fff7c4, #ffd76e); border: 1px solid #c38a22; box-shadow: 0 2px 4px rgba(0, 0, 0, .3); } .hint .typed { color: #b58a21; } .hint.hidden { display: none; } `; let state = null; // { newTab, hints: [{ el, label, node }], typed, root } function isDisabled(el) { return el.disabled === true || el.getAttribute('aria-disabled') === 'true'; } /** 点击点所在的那一层:元素在 shadow DOM 里时要用它自己的 root 查,document 只能查到 host。 */ function hitTest(el, x, y) { const root = el.getRootNode(); const hit = (root.elementFromPoint ? root : document).elementFromPoint(x, y); return !!hit && (hit === el || el.contains(hit)); } /** * 第一块在视口里、而且真的露在最上面的矩形。折行的链接有多块矩形,任何一块能点到就行。 * 被遮挡的判断用 elementFromPoint:透明遮罩、弹窗背后、被 overflow 裁掉的部分都会打到别的元素上。 * 只查中心不够 —— 卡片角上的「×」可能正好压在链接中心,所以再试两个角附近的点。 */ function visibleRect(el) { const vw = window.innerWidth; const vh = window.innerHeight; for (const r of el.getClientRects()) { const left = Math.max(r.left, 0); const top = Math.max(r.top, 0); const right = Math.min(r.right, vw); const bottom = Math.min(r.bottom, vh); if (right - left < 3 || bottom - top < 3) continue; const points = [ [(left + right) / 2, (top + bottom) / 2], [left + 2, top + 2], [right - 2, bottom - 2], ]; if (points.some(([x, y]) => hitTest(el, x, y))) return { left, top, right, bottom }; } return null; } /** * 按文档顺序收集,遇到 open shadow root 就钻进去(Web Components 做的按钮、工具栏)。 * closed shadow root 从外面拿不到,只能放弃。 */ function candidates() { const out = []; const walk = (root) => { for (const el of root.querySelectorAll('*')) { if (el.hasAttribute(UI_ATTR)) continue; if (el.matches(CLICKABLE)) out.push(el); if (el.shadowRoot) walk(el.shadowRoot); } }; walk(document); return out; } /** 能在新标签打开的地址;javascript: 链接和 SVG 里的 (href 不是字符串)不算。 */ function linkUrl(el) { if (!(el instanceof HTMLAnchorElement || el instanceof HTMLAreaElement)) return null; return el.href && !/^javascript:/i.test(el.href) ? el.href : null; } function collect(linksOnly) { const out = []; const seen = new Set(); for (const el of candidates()) { // 之类的全局委托:整页都「可点」,提示出在左上角毫无意义 if (el === document.body || el === document.documentElement || isDisabled(el)) continue; if (linksOnly && !linkUrl(el)) continue; const st = getComputedStyle(el); if (st.visibility === 'hidden' || st.visibility === 'collapse') continue; const rect = visibleRect(el); if (!rect) continue; // 包着可见控件的