油猴脚本:快速聚焦bilibili搜索框
bilibili油猴脚本,按 / 快速聚焦搜索框,按 Esc 取消聚焦
- 页面任意位置(非输入状态)按
/→ 光标跳入顶部搜索框 - 搜索框聚焦时按
Esc→ 失焦,面板收起 - 在评论框、弹幕框等输入区域按
/→ 正常输入斜杠,不会跳走
// ==UserScript==
// @name Bilibili 按 / 聚焦搜索框,Esc 取消
// @namespace http://tampermonkey.net/
// @version 1.1
// @description 在B站按 / 聚焦顶部搜索框,按 Esc 取消聚焦
// @author 111
// @match https://www.bilibili.com/*
// @match https://search.bilibili.com/*
// @grant none
// @run-at document-idle
// ==/UserScript==
(function () {
'use strict';
// 查找搜索框(兼容不同页面结构)
function getSearchInput() {
return document.querySelector('.nav-search-input')
|| document.querySelector('.center-search__bar input.nav-search-input')
|| document.querySelector('#nav-searchform input.nav-search-input')
|| document.querySelector('.search-input-wrap input.search-input-el') // 结果页正文搜索框
|| document.querySelector('input.search-input-el'); // 兜底
}
// 判断当前焦点是否在输入类元素中
function isTypingInInput() {
const el = document.activeElement;
if (!el) return false;
const tag = el.tagName.toLowerCase();
if (tag === 'input' || tag === 'textarea' || tag === 'select') return true;
if (el.isContentEditable) return true;
return false;
}
document.addEventListener('keydown', function (e) {
// ---------- 1. Esc:取消搜索框聚焦 ----------
if (e.key === 'Escape') {
const input = getSearchInput();
// 只有当前焦点确实在搜索框上时才处理
if (input && document.activeElement === input) {
e.preventDefault();
input.blur(); // 失焦
// 可选:收起搜索面板(B站聚焦时会展开下拉面板)
// 有些页面失焦后下拉不会自动收起,这里兜底处理
const panel = document.querySelector('.nav-search-panel');
if (panel) {
panel.style.display = 'none';
}
}
return;
}
// ---------- 2. "/":聚焦搜索框 ----------
if (e.key !== '/' || e.ctrlKey || e.altKey || e.metaKey) return;
if (isTypingInInput()) return;
const input = getSearchInput();
if (!input) return;
e.preventDefault();
input.focus();
const len = input.value.length;
try {
input.setSelectionRange(len, len);
} catch (_) {}
}, true);
})();