一个油猴脚本(v2.9)的介绍:划词即搜、多引擎并排、按钮与弹窗双向拖拽,样式零污染。
一、它解决的是什么问题
日常浏览网页时,”想搜一下”这个动作的路径往往是别扭的:
- 看到一段感兴趣的文字,要先选中、复制,再切标签页,再打开搜索引擎,再粘贴、回车;
- 想同时看百度和 Google 的结果,得开两次搜索、来回对照;
- 在企业管理类网站(比如查企业)上翻到一个名字,想顺手查一下工商信息,还得重新输一遍。
这个脚本做的事情很简单:在每个页面的右下角放一颗半透明的悬浮球。点一下,弹出搜索框,里面已经替你填好了当前选中或页面搜索框里的关键词,再点一下引擎按钮,结果在新标签页打开。
一句话概括它的设计取向:它不做”搜索引擎聚合页面”,而是做一个能在任何页面上”顺手搜”的入口。
二、它长什么样
- 悬浮球:44×44 圆形,蓝色(
#2563eb),默认半透明(opacity: 0.4),鼠标悬停加深到 0.65。不抢视线,但永远在那儿。 - 弹窗:360px 宽,半透明白底 + 毛玻璃观感,3×2 网格排列六个引擎按钮,右上角一个
×。 - 位置关系:弹窗默认出现在悬浮球正上方;上方空间不够时自动翻到球的下方;左右和上下都会做边界收敛,不会被挤出屏幕。
- 位置记忆:拖到哪儿,下次打开还在哪儿(存
localStorage)。
三、怎么装上
- 浏览器装好 Tampermonkey(篡改猴)扩展;
- 扩展面板里点「新建脚本」,把编辑器里的模板内容全选删除;
- 粘贴脚本全文,
Ctrl/Cmd + S保存; - 随便打开一个网页,右下角应该能看到那颗蓝色小球。
脚本头部的 @match *://*/* 表示全站生效。如果你只想在特定站点用,把它改成具体的,比如:
// @match *://*.baidu.com/*
// @match *://*.github.com/*
// @match *://www.riskbird.com/*
改窄 @match 是好习惯——少一个常驻脚本,少一份和页面打架的风险。
四、六个内置引擎
| 名称 | 用途 |
|---|---|
| 百度 | 通用中文搜索 |
| 谷歌 | 通用搜索 / 英文资料 |
| Riskbird | 企业工商信息查询 |
| 高德 | 地点、POI 检索 |
| Github | 代码与仓库检索 |
| 豆瓣 | 书影音条目检索 |
从这组配置能看出作者的使用场景:通用搜索 + 企业查询 + 地理检索三件套,典型的信息搜集 / 调研工作流。
加一个自己的引擎
引擎列表就是一个数组,加一行就行:
const ENGINES = [
{ name: "百度", url: "https://www.baidu.com/s?wd={q}" },
// ...
{ name: "知乎", url: "https://www.zhihu.com/search?type=content&q={q}" },
{ name: "Bing", url: "https://www.bing.com/search?q={q}" }
];
{q} 是占位符,点击时会用 encodeURIComponent 编码后替换。注意按钮是 3 列网格,引擎数量最好是 3 的倍数,否则最后一行会缺角。
五、几个值得学的实现细节
1. 用 Shadow DOM 做样式隔离
把按钮和弹窗塞进一个 attachShadow({ mode: 'open' }) 里,再配一句 :host { all: initial; },脚本的样式和页面的样式就互不干扰了。
这是这类”浮层脚本”最容易翻车的地方:如果你直接把 <div> 挂到 document.body,页面上的 div { padding: 12px } 或者某个 CSS 框架的全局重置,可能会把你的弹窗撑变形。
还要注意宿主容器这几行:
'position:fixed!important',
'width:0!important', 'height:0!important',
'pointer-events:none!important',
'z-index:2147483647!important'
宿主本身零尺寸、且不接收鼠标事件(pointer-events:none),只在里面的按钮和弹窗上单独打开 pointer-events:auto。这样即便它铺在页面最上层,也不会挡住下面任何内容的点击。
2. 双向拖拽:一套坐标做唯一真源
这是这个脚本最值得看的部分。
很多”按钮 + 弹窗联动”的实现会维护两套坐标,然后写一堆同步逻辑,拖几次就开始漂移。这里的做法是:state 里只把按钮位置当作基准,弹窗位置永远由按钮推导出来。
function positionPopupFromBtn(pop) {
const popH = pop.offsetHeight || 180;
let popTop = state.btnTop - popH - GAP; // 优先放上方
let popLeft = state.btnLeft;
popLeft = Math.max(8, Math.min(popLeft, window.innerWidth - POP_W - 8));
if (popTop < 8) { // 上方放不下 → 翻到下方
popTop = state.btnTop + BTN_SIZE + GAP;
}
if (popTop + popH > window.innerHeight - 8) { // 垂直兜底
popTop = Math.max(8, window.innerHeight - popH - 8);
}
state.popLeft = popLeft;
state.popTop = popTop;
}
拖按钮时:改按钮坐标 → 重算弹窗坐标 → 一起重排。
拖弹窗时:先按鼠标算弹窗坐标 → 把按钮”钉”在弹窗下方 GAP 像素处 → 再一起重排。
于是”拖动弹窗时图标同步移动”这件事,不是靠监听、不是靠同步,而是从定义上就成立。整个脚本没有一处坐标同步的补丁代码,这是它干净的原因。
3. 区分”点击”和”拖动”
悬浮球既要能点(打开弹窗),又要能拖。这里用一个 moved 标志位解决:
btn.addEventListener('mousedown', e => { dragBtn.on = true; dragBtn.moved = false; /* ... */ });
document.addEventListener('mousemove', e => {
if (dragBtn.on) { dragBtn.moved = true; /* 更新位置 */ }
});
btn.addEventListener('click', e => {
if (dragBtn.moved) return; // 拖过就不当成点击
// ...打开弹窗
});
简单可靠,比用时间阈值或位移阈值判断更不容易误判。
4. 取词的优先级
点开弹窗时,输入框的内容按这个顺序填充:
window.getSelection()—— 当前页面选中的文字;- 常见搜索框的选择器列表:
input[name="wd"](百度)、input[name="q"]、input[type="search"]、placeholder含「搜索 / 请输入 / 企业名称」的输入框; .el-input__inner—— Element UI 的输入框类名,很多国内企业信息站的标配。
这基本覆盖了”我想搜的东西正好就在页面上”的绝大多数场景:要么你选中了它,要么它就在页面搜索框里。
5. 保活机制
const obs = new MutationObserver(() => {
if (!document.getElementById(HOST_ID) && document.body) { obs.disconnect(); init(); }
});
obs.observe(document.documentElement, { childList: true, subtree: true });
setInterval(() => {
if (!document.getElementById(HOST_ID) && document.body) init();
}, 1000);
MutationObserver 负责在节点被移除时立刻重建,1 秒轮询作为兜底。两者看着冗余,但对 SPA 站点(路由切换重渲染 DOM)和某些会清理 body 子节点的页面来说,双保险是必要的——否则脚本会在某些页面上”莫名其妙消失”。
六、已知的边界与可以再打磨的地方
用下来有几个点值得注意,也算给想改的人一份清单:
1. 进不了 iframe。 脚本运行在顶层文档,页面里嵌的 iframe 内部它覆盖不到。z-index 再高也只在本文档内有效。
2. 顶层 dialog / 全屏元素会盖住它。 浏览器 top layer(<dialog open>、全屏模式)永远在最上方,z-index 管不了。
3. 窗口缩放后位置不纠偏。 保存的是绝对像素坐标,从大屏拖到小屏,或者把窗口缩窄,球可能跑到可视区外。补一块 resize 监听、把坐标重新 clamp 一遍就行:
window.addEventListener('resize', () => {
state.btnLeft = Math.max(0, Math.min(state.btnLeft, window.innerWidth - BTN_SIZE));
state.btnTop = Math.max(0, Math.min(state.btnTop, window.innerHeight - BTN_SIZE));
positionPopupFromBtn(pop);
applyLayout(btn, pop);
});
4. 关闭弹窗的判断可以更稳。 现在用 host.contains(e.target) 判断点击是否在浮层内部。Shadow DOM 会把事件目标重定向为宿主元素,配合 composedPath() 更严谨:
document.addEventListener('mousedown', e => {
if (!e.composedPath().includes(host)) pop.style.display = 'none';
});
5. 隐藏状态下测不到真实高度。 display: none 时 offsetHeight 为 0,positionPopupFromBtn 里退化成 || 180 的估算值。实际影响不大(打开时会重算),但如果想让关闭状态下的位置也精确,可以在打开后再测一次真实高度并重排。
6. 取词可能不干净。 跨段落选中时会带上换行和多余空白,搜出来的结果可能偏;在长文页面上尤其明显。可以加一步清洗:折叠连续空白、截断到合理长度(比如 100 字符)。
7. 缺少键盘入口。 目前只能鼠标点。加一条全局快捷键(比如 Alt+S 打开弹窗、Esc 关闭)会明显好用——尤其对习惯键盘的人。
七、小结
这个脚本的价值不在功能有多重,而在于克制:
- 一个悬浮球,不占位、不打扰;
- 一次点击完成”取词 → 选引擎 → 打开结果”;
- 不用时它半透明地待在角落,用得着时刚好在你手边;
- 实现上 Shadow DOM 做隔离、单坐标源做位置、双保险做保活——三处该讲究的地方都讲究了。
如果你每天要在多个搜索引擎和企业信息站之间来回切,这类脚本省下的不是一次点击,而是每次搜索前那三五秒的上下文切换。装机量不大,但属于装上就不会卸的那一类。
脚本头部声明为 @run-at document-idle,配合 MutationObserver 与定时兜底,在 SPA 站点上也能稳定存活。建议按自己的常用站点收窄 @match,减少无谓的常驻开销。
// ==UserScript==
// @name 多搜索引擎弹窗搜索
// @namespace http://tampermonkey.net/
// @version 2.9
// @description 悬浮图标与弹窗双向联动拖拽,拖动弹窗时图标同步移动
// @author You
// @match *://*/*
// @run-at document-idle
// @grant none
// ==/UserScript==
(function () {
'use strict';
const ENGINES = [
{ name: "百度", url: "https://www.baidu.com/s?wd={q}" },
{ name: "谷歌", url: "https://www.google.com/search?q={q}" },
{ name: "Riskbird", url: "https://www.riskbird.com/search/company?keyword={q}" },
{ name: "高德", url: "https://ditu.amap.com/ssr/search?query_type=TQUERY&query={q}" },
{ name: "Github", url: "https://github.com/search?q={q}" },
{ name: "豆瓣", url: "https://www.douban.com/search?q={q}" }
];
const HOST_ID = '__ms_shadow_host__';
const BTN_SIZE = 44;
const POP_W = 360;
const GAP = 8;
// 统一状态:按钮位置为基准,弹窗位置由按钮位置计算
let state = {
btnLeft: 0,
btnTop: 0,
popLeft: 0,
popTop: 0
};
let dragBtn = { on: false, moved: false, ox: 0, oy: 0 };
let dragPop = { on: false, ox: 0, oy: 0 };
function getSearchInputText() {
const selectors = [
'input[name="wd"]',
'input[name="q"]',
'input[name="query"]',
'input[type="search"]',
'input[placeholder*="请输入"]',
'input[placeholder*="搜索"]',
'input[placeholder*="企业名称"]',
'.el-input__inner'
];
for (const sel of selectors) {
const el = document.querySelector(sel);
if (el && el.value?.trim()) return el.value.trim();
}
return '';
}
function applyLayout(btn, pop) {
btn.style.left = state.btnLeft + 'px';
btn.style.top = state.btnTop + 'px';
pop.style.left = state.popLeft + 'px';
pop.style.top = state.popTop + 'px';
}
// 根据按钮位置重新计算弹窗位置
function positionPopupFromBtn(pop) {
const popH = pop.offsetHeight || 180;
let popTop = state.btnTop - popH - GAP;
let popLeft = state.btnLeft;
// 水平边界
popLeft = Math.max(8, Math.min(popLeft, window.innerWidth - POP_W - 8));
// 上方放不下就放按钮下方
if (popTop < 8) {
popTop = state.btnTop + BTN_SIZE + GAP;
}
// 垂直边界兜底
if (popTop + popH > window.innerHeight - 8) {
popTop = Math.max(8, window.innerHeight - popH - 8);
}
state.popLeft = popLeft;
state.popTop = popTop;
}
function saveBtnPos() {
localStorage.setItem(
'ms_pos',
JSON.stringify({
l: Math.round(state.btnLeft),
t: Math.round(state.btnTop)
})
);
}
function init() {
if (document.getElementById(HOST_ID)) return;
if (!document.body) return;
const host = document.createElement('div');
host.id = HOST_ID;
host.style.cssText = [
'position:fixed!important',
'top:0!important',
'left:0!important',
'width:0!important',
'height:0!important',
'overflow:visible!important',
'z-index:2147483647!important',
'pointer-events:none!important',
'background:0 0!important',
'border:0!important',
'margin:0!important',
'padding:0!important'
].join(';');
document.body.appendChild(host);
const shadow = host.attachShadow({ mode: 'open' });
const style = document.createElement('style');
style.textContent = `
:host { all: initial; }
* { box-sizing: border-box; margin: 0; padding: 0; }
.s-btn {
position: fixed; width: 44px; height: 44px; border-radius: 50%;
background: #2563eb; color: #fff; display: flex; align-items: center;
justify-content: center; cursor: grab; z-index: 2147483647;
box-shadow: 0 2px 10px rgba(0,0,0,.25); user-select: none;
font-size: 18px; pointer-events: auto; line-height: 1; border: none;
font-family: system-ui, -apple-system, sans-serif;
opacity:0.4;
transition: opacity 0.2s;
}
.s-btn:hover { opacity:0.65; }
.s-btn:active { cursor: grabbing; }
.s-pop {
position: fixed; width: 360px; background: rgba(255,255,255,0.75); border-radius: 10px;
box-shadow: 0 4px 24px rgba(0,0,0,.22); z-index: 2147483647;
padding: 14px 14px 12px; display: none; pointer-events: auto;
font-family: system-ui, -apple-system, sans-serif;
cursor: grab;
}
.s-pop:active { cursor: grabbing; }
.s-pop input {
width: 100%; padding: 9px 12px; border: 1px solid rgba(204,204,204,.6);
border-radius: 6px; font-size: 14px; margin-bottom: 10px;
outline: none; font-family: inherit;
background: rgba(255,255,255,0.55);
color: #111;
pointer-events:auto;
cursor:text;
}
.s-pop input:focus {
border-color: rgba(37,99,235,.8);
box-shadow: 0 0 0 2px rgba(37,99,235,.18);
background: rgba(255,255,255,0.75);
}
.s-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; }
.s-grid button {
padding: 7px 4px; border: none; border-radius: 6px;
background: rgba(37,99,235,.72); color: #fff; cursor: pointer;
font-size: 13px; font-family: inherit; pointer-events: auto;
transition: background .15s;
}
.s-grid button:hover { background: rgba(29,78,216,.88); }
.s-close {
position: absolute; top: 6px; right: 8px; cursor: pointer;
font-size: 18px; color: rgba(153,153,153,0.85); pointer-events: auto;
line-height: 1; background: none; border: none; padding: 4px;
}
.s-close:hover { color: #333; }
`;
shadow.appendChild(style);
const btn = document.createElement('div');
btn.className = 's-btn';
btn.textContent = '🔍';
shadow.appendChild(btn);
const pop = document.createElement('div');
pop.className = 's-pop';
pop.innerHTML =
'<span class="s-close">×</span>' +
'<input placeholder="关键词,可自动读取页面搜索框内容">' +
'<div class="s-grid"></div>';
shadow.appendChild(pop);
const input = pop.querySelector('input');
const grid = pop.querySelector('.s-grid');
const closeBtn = pop.querySelector('.s-close');
ENGINES.forEach(en => {
const b = document.createElement('button');
b.textContent = en.name;
b.dataset.url = en.url;
grid.appendChild(b);
});
closeBtn.onclick = () => {
pop.style.display = 'none';
};
// 初始化按钮位置
const saved = JSON.parse(localStorage.getItem('ms_pos') || '{}');
if (saved.l != null && saved.t != null) {
state.btnLeft = saved.l;
state.btnTop = saved.t;
} else {
state.btnLeft = window.innerWidth - BTN_SIZE - 20;
state.btnTop = window.innerHeight - BTN_SIZE - 80;
}
positionPopupFromBtn(pop);
applyLayout(btn, pop);
// 按钮拖拽
btn.addEventListener('mousedown', e => {
if (e.button !== 0) return;
dragBtn.on = true;
dragBtn.moved = false;
dragBtn.ox = e.clientX - state.btnLeft;
dragBtn.oy = e.clientY - state.btnTop;
e.preventDefault();
});
// 弹窗拖拽:明确带动按钮
pop.addEventListener('mousedown', e => {
if (e.target === input || e.target.closest('button')) return;
if (e.button !== 0) return;
dragPop.on = true;
dragPop.ox = e.clientX - state.popLeft;
dragPop.oy = e.clientY - state.popTop;
e.preventDefault();
});
document.addEventListener('mousemove', e => {
if (dragBtn.on) {
dragBtn.moved = true;
state.btnLeft = Math.max(0, Math.min(e.clientX - dragBtn.ox, window.innerWidth - BTN_SIZE));
state.btnTop = Math.max(0, Math.min(e.clientY - dragBtn.oy, window.innerHeight - BTN_SIZE));
positionPopupFromBtn(pop);
applyLayout(btn, pop);
}
if (dragPop.on) {
// 先移动弹窗
state.popLeft = Math.max(0, Math.min(e.clientX - dragPop.ox, window.innerWidth - POP_W));
state.popTop = Math.max(0, Math.min(e.clientY - dragPop.oy, window.innerHeight - (pop.offsetHeight || 180)));
// 按钮始终跟随弹窗底部
state.btnLeft = state.popLeft;
state.btnTop = state.popTop + (pop.offsetHeight || 180) + GAP;
// 按钮边界
state.btnLeft = Math.min(state.btnLeft, window.innerWidth - BTN_SIZE);
state.btnTop = Math.min(state.btnTop, window.innerHeight - BTN_SIZE);
applyLayout(btn, pop);
}
});
document.addEventListener('mouseup', () => {
if (dragBtn.on && dragBtn.moved) saveBtnPos();
if (dragPop.on) saveBtnPos();
dragBtn.on = false;
dragPop.on = false;
});
btn.addEventListener('click', e => {
if (dragBtn.moved) return;
let txt = '';
try { txt = window.getSelection().toString().trim(); } catch (_) {}
if (!txt) txt = getSearchInputText();
if (txt) input.value = txt;
pop.style.display = 'block';
positionPopupFromBtn(pop);
applyLayout(btn, pop);
input.focus();
});
grid.addEventListener('click', e => {
if (e.target.tagName !== 'BUTTON') return;
const q = input.value.trim();
if (!q) return;
window.open(e.target.dataset.url.replace('{q}', encodeURIComponent(q)), '_blank');
pop.style.display = 'none';
});
input.addEventListener('keydown', e => {
if (e.key === 'Enter') grid.querySelector('button').click();
});
document.addEventListener('mousedown', e => {
if (!host.contains(e.target)) pop.style.display = 'none';
});
const obs = new MutationObserver(() => {
if (!document.getElementById(HOST_ID) && document.body) {
obs.disconnect();
init();
}
});
obs.observe(document.documentElement, { childList: true, subtree: true });
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
setInterval(() => {
if (!document.getElementById(HOST_ID) && document.body) init();
}, 1000);
})();