|
|
本帖最后由 qjldw 于 2026-11-18 23:46 编辑
- // ==UserScript==
- // @name 无忧论坛 · 站内搜索增强(百度 site:)
- // @namespace https://bbs.wuyou.net/
- // @version 3.2.1
- // @description 无忧论坛取消站内搜索后的替代方案。①论坛页:右上角搜索框,支持百度联想词、搜索历史、本版块限定、多引擎切换;②百度结果页:自动把 wuyou.net 条目卡片化标注,并提供「只看无忧站内」筛选。
- // @match *://*.wuyou.net/*
- // @match *://www.baidu.com/s*
- // @run-at document-idle
- // @noframes
- // @grant none
- // ==/UserScript==
- (function () {
- 'use strict';
- /* ================== 配置 ================== */
- const SITE = 'wuyou.net'; // 站内范围(site:wuyou.net)
- const DEFAULT_ENGINE = 'baidu'; // baidu | bing | google
- const ENGINES = {
- baidu: { label: '百度', url: 'https://www.baidu.com/s?ie=utf-8&wd=' },
- bing: { label: '必应', url: 'https://cn.bing.com/search?q=' },
- google: { label: '谷歌', url: 'https://www.google.com/search?q=' }
- };
- const SUGGEST = true; // 百度联想词(JSONP)
- const HIJACK_SITE_SEARCH = true; // 是否接管站点自带的 search.php 搜索框(VIP/将军级用户可设 false 保留原功能)
- const HIST_MAX = 8; // 搜索历史条数
- const HOTKEY = 's'; // Alt+S 聚焦搜索框
- /* ========================================== */
- /* 站点判断:百度搜索结果页 vs 论坛页 */
- const onBaiduSerp = /^(www\.)?baidu\.com$/i.test(location.hostname) && location.pathname.indexOf('/s') === 0;
- if (onBaiduSerp) { initBaiduSerp(); } else { initForum(); }
- /* ==========================================================
- 一、论坛页:搜索框
- ========================================================== */
- function initForum() {
- const CSS = `
- #wys-panel{position:fixed;top:34px;right:12px;z-index:2147483100;display:flex;align-items:center;
- font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif;color:#333;}
- #wys-bar{display:flex;align-items:center;gap:4px;padding:4px 6px;border-radius:999px;
- background:rgba(255,255,255,.96);border:1px solid #d7e2ee;box-shadow:0 2px 12px rgba(0,0,0,.18);}
- #wys-input{width:190px;height:26px;padding:0 10px;border:1px solid #cfdae6;border-radius:999px;
- outline:none;font-size:13px;background:#f7fafd;color:#222;box-sizing:border-box;
- transition:border-color .15s,box-shadow .15s;}
- #wys-input:focus{border-color:#3b82c4;background:#fff;box-shadow:0 0 0 3px rgba(59,130,196,.15);}
- #wys-engine{height:26px;border:1px solid #cfdae6;border-radius:999px;background:#fff;
- font-size:12px;color:#333;padding:0 2px;outline:none;cursor:pointer;}
- #wys-go{height:28px;padding:0 12px;border:0;border-radius:999px;background:#2f6fb5;color:#fff;
- font-size:12px;cursor:pointer;white-space:nowrap;}
- #wys-go:hover{background:#255c99;}
- #wys-min{width:20px;height:26px;border:0;background:transparent;color:#93a5b8;cursor:pointer;font-size:14px;line-height:1;}
- #wys-min:hover{color:#2f6fb5;}
- #wys-board-wrap{display:flex;align-items:center;gap:2px;font-size:12px;color:#556;cursor:pointer;white-space:nowrap;}
- #wys-board-wrap input{margin:0;cursor:pointer;}
- #wys-open{display:none;width:40px;height:40px;border:0;border-radius:50%;background:#2f6fb5;color:#fff;
- font-size:13px;cursor:pointer;box-shadow:0 3px 12px rgba(0,0,0,.25);}
- #wys-open:hover{background:#255c99;}
- #wys-panel[data-min="1"] #wys-bar{display:none;}
- #wys-panel[data-min="1"] #wys-open{display:block;}
- #wys-sug{position:fixed;z-index:2147483300;display:none;max-height:250px;overflow:auto;box-sizing:border-box;
- background:#fff;border:1px solid #d7e2ee;border-radius:8px;box-shadow:0 8px 22px rgba(15,35,60,.14);}
- #wys-sug .sug-cap{padding:5px 10px;font-size:11px;color:#9aabbd;background:#fafcfe;border-bottom:1px solid #eef3f8;}
- #wys-sug .sug-item{padding:6px 10px;font-size:12px;color:#33475b;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
- #wys-sug .sug-item:hover,#wys-sug .sug-item.on{background:#eef5fc;color:#2f6fb5;}
- @media (max-width:620px){
- #wys-panel{left:8px;right:8px;justify-content:flex-end;}
- #wys-bar{width:100%;flex-wrap:wrap;justify-content:flex-end;}
- #wys-input{flex:1 1 110px;width:auto;min-width:96px;}
- }`;
- const KEY = { engine: 'wys.engine', min: 'wys.min', board: 'wys.board', hist: 'wys.hist' };
- const load = (k, d) => { try { const v = localStorage.getItem(k); return v === null ? d : v; } catch (e) { return d; } };
- const save = (k, v) => { try { localStorage.setItem(k, v); } catch (e) { /* 忽略 */ } };
- // 当前版块号:/forum-10-1.html → 10
- const boardId = (location.pathname.match(/\/forum-(\d+)-/) || [])[1] || null;
- let engine = load(KEY.engine, DEFAULT_ENGINE);
- if (!ENGINES[engine]) engine = DEFAULT_ENGINE;
- const style = document.createElement('style');
- style.textContent = CSS;
- document.head.appendChild(style);
- const panel = document.createElement('div');
- panel.id = 'wys-panel';
- panel.innerHTML =
- '<div id="wys-bar">' +
- '<input id="wys-input" type="search" placeholder="搜索无忧论坛(回车)" autocomplete="off" spellcheck="false">' +
- (boardId ? '<label id="wys-board-wrap" title="只搜当前版块(inurl:forum-' + boardId + ')"><input type="checkbox" id="wys-board">本版块</label>' : '') +
- '<select id="wys-engine" title="搜索引擎"></select>' +
- '<button id="wys-go" type="button" title="搜索">搜索</button>' +
- '<button id="wys-min" type="button" title="收起">—</button>' +
- '</div>' +
- '<button id="wys-open" type="button" title="展开(Alt+S)">搜</button>';
- const sugBox = document.createElement('div');
- sugBox.id = 'wys-sug';
- document.body.appendChild(panel);
- document.body.appendChild(sugBox);
- const input = panel.querySelector('#wys-input');
- const select = panel.querySelector('#wys-engine');
- const goBtn = panel.querySelector('#wys-go');
- const minBtn = panel.querySelector('#wys-min');
- const openBtn = panel.querySelector('#wys-open');
- const boardBox = panel.querySelector('#wys-board');
- Object.keys(ENGINES).forEach(function (id) {
- const o = document.createElement('option');
- o.value = id;
- o.textContent = ENGINES[id].label;
- select.appendChild(o);
- });
- select.value = engine;
- if (boardBox) boardBox.checked = load(KEY.board, '0') === '1';
- const setMin = (v) => { panel.dataset.min = v ? '1' : '0'; save(KEY.min, v ? '1' : '0'); };
- // 默认收起:只留一个圆形「搜」钮,避免遮挡 Discuz 页头右侧的登录/注册区
- setMin(load(KEY.min, '1') === '1');
- /* ---------- 历史记录 ---------- */
- function getHist() {
- try { const a = JSON.parse(load(KEY.hist, '[]')); return Array.isArray(a) ? a : []; } catch (e) { return []; }
- }
- function pushHist(kw) {
- const a = getHist().filter(function (x) { return x !== kw; });
- a.unshift(kw);
- save(KEY.hist, JSON.stringify(a.slice(0, HIST_MAX)));
- }
- /* ---------- 搜索 ---------- */
- function buildQuery(kw, boardOnly) {
- let q = 'site:' + SITE + ' ' + kw;
- if (boardOnly && boardId) q += ' inurl:forum-' + boardId;
- return q;
- }
- function go() {
- const kw = input.value.trim();
- if (!kw) { input.focus(); return; }
- pushHist(kw);
- hideSug();
- const q = buildQuery(kw, !!(boardBox && boardBox.checked));
- const url = ENGINES[engine].url + encodeURIComponent(q);
- const w = window.open(url, '_blank');
- if (!w) location.href = url; // 弹窗被拦截时降级
- }
- goBtn.addEventListener('click', go);
- input.addEventListener('keydown', function (e) {
- if (e.key === 'Enter') {
- e.preventDefault();
- const on = sugBox.querySelector('.sug-item.on');
- if (sugBox.style.display === 'block' && on) input.value = on.dataset.q; // 回车选高亮联想词
- go();
- } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
- const items = Array.prototype.slice.call(sugBox.querySelectorAll('.sug-item'));
- if (!items.length || sugBox.style.display !== 'block') return;
- e.preventDefault();
- let idx = items.findIndex(function (n) { return n.classList.contains('on'); });
- idx = e.key === 'ArrowDown' ? Math.min(items.length - 1, idx + 1) : Math.max(0, idx - 1);
- items.forEach(function (n) { n.classList.remove('on'); });
- items[idx].classList.add('on');
- input.value = items[idx].dataset.q;
- } else if (e.key === 'Escape') {
- input.value = '';
- input.blur();
- hideSug();
- }
- });
- minBtn.addEventListener('click', function () { setMin(true); });
- openBtn.addEventListener('click', function () {
- setMin(false); input.focus();
- if (!input.value.trim()) showHistory();
- });
- select.addEventListener('change', function () { engine = select.value; save(KEY.engine, engine); });
- if (boardBox) boardBox.addEventListener('change', function () { save(KEY.board, boardBox.checked ? '1' : '0'); });
- document.addEventListener('keydown', function (e) {
- if (e.altKey && !e.ctrlKey && !e.metaKey && e.key && e.key.toLowerCase() === HOTKEY) {
- e.preventDefault(); setMin(false); input.focus(); input.select();
- }
- });
- /* ---------- 联想词 + 历史(JSONP) ---------- */
- let sugTimer = null, sugSeq = 0;
- const sugCache = Object.create(null);
- function hideSug() { sugBox.style.display = 'none'; sugBox.innerHTML = ''; }
- function placeSug() {
- const r = input.getBoundingClientRect();
- sugBox.style.left = Math.max(8, r.left) + 'px';
- sugBox.style.top = (r.bottom + 6) + 'px';
- sugBox.style.width = Math.max(240, r.width) + 'px';
- }
- function renderItems(list, cap) {
- if (!list || !list.length) { hideSug(); return; }
- sugBox.innerHTML =
- '<div class="sug-cap">' + cap + '</div>' +
- list.map(function (q) {
- return '<div class="sug-item" data-q="' + q.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<') + '">' +
- q.replace(/&/g, '&').replace(/</g, '<') + '</div>';
- }).join('');
- placeSug();
- sugBox.style.display = 'block';
- }
- function showHistory() {
- const h = getHist();
- if (!h.length) return;
- renderItems(h, '最近搜索');
- }
- function fetchSug(kw) {
- if (sugCache[kw]) { renderItems(sugCache[kw], '百度联想'); return; }
- const cb = 'wysSug' + (++sugSeq) + '_' + Date.now();
- let done = false;
- window[cb] = function (data) {
- done = true;
- const list = (data && data.g || []).map(function (x) { return x.q; }).filter(Boolean).slice(0, 10);
- sugCache[kw] = list;
- if (input.value.trim() === kw) renderItems(list, '百度联想'); // 防慢响应覆盖新输入
- cleanup();
- };
- const s = document.createElement('script');
- s.src = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&wd=' +
- encodeURIComponent(kw) + '&cb=' + cb;
- s.onerror = cleanup;
- s.onload = function () { if (!done) cleanup(); };
- function cleanup() {
- try { delete window[cb]; } catch (e) { window[cb] = undefined; }
- if (s.parentNode) s.parentNode.removeChild(s);
- }
- document.head.appendChild(s);
- }
- input.addEventListener('input', function () {
- clearTimeout(sugTimer);
- const kw = input.value.trim();
- if (!kw) { if (SUGGEST) showHistory(); else hideSug(); return; }
- if (!SUGGEST) return;
- sugTimer = setTimeout(function () { fetchSug(kw); }, 300);
- });
- input.addEventListener('focus', function () { if (!input.value.trim()) showHistory(); });
- sugBox.addEventListener('click', function (e) {
- const it = e.target && e.target.closest ? e.target.closest('.sug-item') : null;
- if (!it) return;
- input.value = it.dataset.q;
- hideSug();
- go();
- });
- input.addEventListener('blur', function () { setTimeout(hideSug, 200); });
- window.addEventListener('resize', function () { if (sugBox.style.display === 'block') placeSug(); });
- /* ---------- 接管站点残留的搜索入口 ---------- */
- if (HIJACK_SITE_SEARCH) {
- document.addEventListener('click', function (e) {
- const a = e.target && e.target.closest ? e.target.closest('a[href*="search.php"]') : null;
- if (!a || panel.contains(a)) return;
- e.preventDefault();
- e.stopPropagation();
- setMin(false);
- input.focus();
- input.select();
- if (!input.value.trim()) showHistory();
- }, true);
- document.addEventListener('submit', function (e) {
- const form = e.target;
- if (!form || !form.action || form.action.indexOf('search.php') === -1) return;
- const field = form.querySelector('input[name="srchtxt"], input[name="keywords"], input[name="q"], input[type="text"], input[type="search"]');
- const kw = field && field.value ? field.value.trim() : '';
- e.preventDefault();
- e.stopPropagation();
- if (!kw) { setMin(false); input.focus(); return; }
- input.value = kw;
- go();
- }, true);
- }
- }
- /* ==========================================================
- 二、百度结果页:把 wuyou.net 条目卡片化 + 只看站内
- ========================================================== */
- function initBaiduSerp() {
- const CSS = `
- .wys-hit{position:relative;border-radius:6px;box-shadow:inset 3px 0 0 #2f6fb5;}
- .wys-hit .wys-badge{display:inline-block;margin:0 0 4px;padding:0 6px;line-height:18px;border-radius:3px;
- background:#2f6fb5;color:#fff;font:11px/18px -apple-system,"Microsoft YaHei",sans-serif;vertical-align:middle;}
- body.wys-only-on .wys-other{display:none !important;}
- #wys-only{position:fixed;right:16px;bottom:16px;z-index:2147483400;height:32px;padding:0 14px;
- border:1px solid #cfdae6;border-radius:999px;background:#fff;color:#2f6fb5;cursor:pointer;
- font:12px/30px -apple-system,"Microsoft YaHei",sans-serif;box-shadow:0 3px 14px rgba(15,35,60,.18);}
- #wys-only:hover{border-color:#9dc0e0;background:#f2f8fd;}
- #wys-only[data-on="1"]{background:#2f6fb5;color:#fff;border-color:#2f6fb5;}
- `;
- const style = document.createElement('style');
- style.textContent = CSS;
- document.head.appendChild(style);
- let hitCount = 0;
- let onlyOn = false;
- function findContainer() {
- return document.querySelector('#content_left') || document.querySelector('#results') || null;
- }
- // 判断一个块是否真的命中站内。
- // 注意两点坑:① 有机结果的跳转链接是 baidu.com/link?url=…,href 里看不到目标域名,
- // 域名只出现在「显示网址」那行(cite/.c-showurl)的**可见文本**里;
- // ② 「大家还在搜」这类聚合模块(class 含 result-op)里的搜索链接 href 会带着原查询串,
- // 里面可能就有 wuyou.net,按 href 判断会整块误判,所以必须排除聚合模块、且只认可见文本。
- function isHit(block) {
- if (!block || block.nodeType !== 1) return false;
- if (/result-op/.test(block.className || '')) return false;
- const as = block.querySelectorAll('a');
- for (let i = 0; i < as.length; i++) {
- const href = as[i].getAttribute('href') || '';
- if (/^(?:https?:\/\/)?(?:[a-z0-9-]+\.)*wuyou\.net(?:[\/?#]|$)/i.test(href)) return true; // 真·直链
- if (/wuyou\.net/i.test(as[i].textContent || '')) return true; // 显示出来的网址文本
- }
- const cites = block.querySelectorAll('cite, .c-showurl, .f13');
- for (let j = 0; j < cites.length; j++) {
- if (/wuyou\.net/i.test(cites[j].textContent || '')) return true;
- }
- return false;
- }
- function scan() {
- const box = findContainer();
- if (!box) return;
- const blocks = Array.prototype.slice.call(box.children).filter(function (n) {
- return n.nodeType === 1 && !/^(SCRIPT|STYLE)$/.test(n.tagName);
- });
- if (!blocks.length) return;
- hitCount = 0;
- blocks.forEach(function (b) {
- if (isHit(b)) {
- hitCount++;
- if (!b.classList.contains('wys-hit')) {
- b.classList.add('wys-hit');
- const badge = document.createElement('span');
- badge.className = 'wys-badge';
- badge.textContent = '无忧站内';
- // 放在块内第一个可见元素之前;找不到就插到块首
- const first = b.querySelector('h3, .c-title, .t') || b.firstChild;
- if (first && first.parentNode === b) b.insertBefore(badge, first);
- else b.insertBefore(badge, b.firstChild);
- }
- } else {
- // 上一轮可能误标过(百度异步渲染会替换节点),这里顺手撤回
- if (b.classList.contains('wys-hit')) {
- b.classList.remove('wys-hit');
- const old = b.querySelector('.wys-badge');
- if (old && old.parentNode) old.parentNode.removeChild(old);
- }
- b.classList.add('wys-other');
- }
- });
- updateBtn();
- }
- const btn = document.createElement('button');
- btn.id = 'wys-only';
- btn.type = 'button';
- btn.addEventListener('click', function () {
- onlyOn = !onlyOn;
- document.body.classList.toggle('wys-only-on', onlyOn);
- updateBtn();
- });
- function updateBtn() {
- if (!hitCount) { btn.style.display = 'none'; return; }
- btn.style.display = 'block';
- btn.dataset.on = onlyOn ? '1' : '0';
- btn.textContent = onlyOn ? '显示全部结果' : '只看无忧站内(' + hitCount + '条)';
- }
- function boot() {
- if (!document.body) { setTimeout(boot, 300); return; }
- document.body.appendChild(btn);
- scan();
- // 百度结果是异步/分页加载的,监听变化后重扫
- let t = null;
- const mo = new MutationObserver(function () {
- clearTimeout(t);
- t = setTimeout(scan, 600);
- });
- const box = findContainer() || document.body;
- mo.observe(box, { childList: true, subtree: true });
- }
- boot();
- }
- })();
复制代码
新增默认搜索引擎为必应,并且由于按板块搜索没用,去掉「本版块」打开联想词兜底,但是历史词优先,不要的自己修改
- // ==UserScript==
- // @name 无忧论坛 · 站内搜索增强(默认必应 site:)
- // @namespace https://bbs.wuyou.net/
- // @version 3.3.2
- // @description 无忧论坛取消站内搜索后的替代方案。①论坛页:右上角搜索框,默认走必应 site:,支持 10 条搜索历史、多引擎切换;②结果页(百度 / 必应):自动把 wuyou.net 条目卡片化标注,并提供「只看无忧站内」筛选。
- // @match *://*.wuyou.net/*
- // @match *://*.baidu.com/s*
- // @match *://*.bing.com/search*
- // @run-at document-idle
- // @noframes
- // @grant none
- // ==/UserScript==
- (function () {
- 'use strict';
- /* ================== 配置 ================== */
- const SITE = 'wuyou.net'; // 站内范围(site:wuyou.net)
- const DEFAULT_ENGINE = 'bing'; // baidu | bing | google(默认必应,可随时在下拉里切换)
- const ENGINES = {
- baidu: { label: '百度', url: 'https://www.baidu.com/s?ie=utf-8&wd=' },
- bing: { label: '必应', url: 'https://cn.bing.com/search?q=' },
- google: { label: '谷歌', url: 'https://www.google.com/search?q=' }
- };
- const SUGGEST = true; // 关键词联想(走百度 JSONP)。只在「历史里没有匹配」时才请求,设为 false 则完全不请求
- const HIST_FIRST = true; // 历史优先:输入时先在前缀/包含命中的历史里过滤,命中就只显示历史
- const HIJACK_SITE_SEARCH = true; // 是否接管站点自带的 search.php 搜索框(VIP/将军级用户可设 false 保留原功能)
- const HIST_MAX = 10; // 搜索历史条数
- const HOTKEY = 's'; // Alt+S 聚焦搜索框
- /* ========================================== */
- /* 站点判断:结果页(百度 / 必应)vs 论坛页 */
- const onBaiduSerp = /^(www\.)?baidu\.com$/i.test(location.hostname) && location.pathname.indexOf('/s') === 0;
- const onBingSerp = /^(cn|www)\.bing\.com$/i.test(location.hostname) && location.pathname.indexOf('/search') === 0;
- if (onBaiduSerp) { initSerp('baidu'); }
- else if (onBingSerp) { initSerp('bing'); }
- else { initForum(); }
- /* ==========================================================
- 一、论坛页:搜索框
- ========================================================== */
- function initForum() {
- const CSS = `
- #wys-panel{position:fixed;top:34px;right:12px;z-index:2147483100;display:flex;align-items:center;
- font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif;color:#333;}
- #wys-bar{display:flex;align-items:center;gap:4px;padding:4px 6px;border-radius:999px;
- background:rgba(255,255,255,.96);border:1px solid #d7e2ee;box-shadow:0 2px 12px rgba(0,0,0,.18);}
- #wys-input{width:190px;height:26px;padding:0 10px;border:1px solid #cfdae6;border-radius:999px;
- outline:none;font-size:13px;background:#f7fafd;color:#222;box-sizing:border-box;
- transition:border-color .15s,box-shadow .15s;}
- #wys-input:focus{border-color:#3b82c4;background:#fff;box-shadow:0 0 0 3px rgba(59,130,196,.15);}
- #wys-engine{height:26px;border:1px solid #cfdae6;border-radius:999px;background:#fff;
- font-size:12px;color:#333;padding:0 2px;outline:none;cursor:pointer;}
- #wys-go{height:28px;padding:0 12px;border:0;border-radius:999px;background:#2f6fb5;color:#fff;
- font-size:12px;cursor:pointer;white-space:nowrap;}
- #wys-go:hover{background:#255c99;}
- #wys-min{width:20px;height:26px;border:0;background:transparent;color:#93a5b8;cursor:pointer;font-size:14px;line-height:1;}
- #wys-min:hover{color:#2f6fb5;}
- #wys-open{display:none;width:40px;height:40px;border:0;border-radius:50%;background:#2f6fb5;color:#fff;
- font-size:13px;cursor:pointer;box-shadow:0 3px 12px rgba(0,0,0,.25);}
- #wys-open:hover{background:#255c99;}
- #wys-panel[data-min="1"] #wys-bar{display:none;}
- #wys-panel[data-min="1"] #wys-open{display:block;}
- #wys-sug{position:fixed;z-index:2147483300;display:none;max-height:250px;overflow:auto;box-sizing:border-box;
- background:#fff;border:1px solid #d7e2ee;border-radius:8px;box-shadow:0 8px 22px rgba(15,35,60,.14);}
- #wys-sug .sug-cap{padding:5px 10px;font-size:11px;color:#9aabbd;background:#fafcfe;border-bottom:1px solid #eef3f8;}
- #wys-sug .sug-item{padding:6px 10px;font-size:12px;color:#33475b;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
- #wys-sug .sug-item:hover,#wys-sug .sug-item.on{background:#eef5fc;color:#2f6fb5;}
- @media (max-width:620px){
- #wys-panel{left:8px;right:8px;justify-content:flex-end;}
- #wys-bar{width:100%;flex-wrap:wrap;justify-content:flex-end;}
- #wys-input{flex:1 1 110px;width:auto;min-width:96px;}
- }`;
- const KEY = { engine: 'wys.engine', min: 'wys.min', hist: 'wys.hist' };
- const load = (k, d) => { try { const v = localStorage.getItem(k); return v === null ? d : v; } catch (e) { return d; } };
- const save = (k, v) => { try { localStorage.setItem(k, v); } catch (e) { /* 忽略 */ } };
- let engine = load(KEY.engine, DEFAULT_ENGINE);
- if (!ENGINES[engine]) engine = DEFAULT_ENGINE;
- // 默认引擎迁移:只做一次,把本地存着的旧默认值(百度)覆盖成必应。
- // 之后你在下拉里手动选的其他引擎不会被再改回来。
- const ENGINE_STAMP = 'v322-bing';
- if (load('wys.engineStamp', '') !== ENGINE_STAMP) {
- engine = DEFAULT_ENGINE;
- save(KEY.engine, engine);
- save('wys.engineStamp', ENGINE_STAMP);
- }
- const style = document.createElement('style');
- style.textContent = CSS;
- document.head.appendChild(style);
- const panel = document.createElement('div');
- panel.id = 'wys-panel';
- panel.innerHTML =
- '<div id="wys-bar">' +
- '<input id="wys-input" type="search" placeholder="搜索无忧论坛(回车)" autocomplete="off" spellcheck="false">' +
- '<select id="wys-engine" title="搜索引擎"></select>' +
- '<button id="wys-go" type="button" title="搜索">搜索</button>' +
- '<button id="wys-min" type="button" title="收起">—</button>' +
- '</div>' +
- '<button id="wys-open" type="button" title="展开(Alt+S)">搜</button>';
- const sugBox = document.createElement('div');
- sugBox.id = 'wys-sug';
- document.body.appendChild(panel);
- document.body.appendChild(sugBox);
- const input = panel.querySelector('#wys-input');
- const select = panel.querySelector('#wys-engine');
- const goBtn = panel.querySelector('#wys-go');
- const minBtn = panel.querySelector('#wys-min');
- const openBtn = panel.querySelector('#wys-open');
- Object.keys(ENGINES).forEach(function (id) {
- const o = document.createElement('option');
- o.value = id;
- o.textContent = ENGINES[id].label;
- select.appendChild(o);
- });
- select.value = engine;
- const setMin = (v) => { panel.dataset.min = v ? '1' : '0'; save(KEY.min, v ? '1' : '0'); };
- // 默认收起:只留一个圆形「搜」钮,避免遮挡 Discuz 页头右侧的登录/注册区
- setMin(load(KEY.min, '1') === '1');
- /* ---------- 历史记录 ---------- */
- function getHist() {
- try { const a = JSON.parse(load(KEY.hist, '[]')); return Array.isArray(a) ? a.slice(0, HIST_MAX) : []; } catch (e) { return []; }
- }
- function pushHist(kw) {
- const a = getHist().filter(function (x) { return x !== kw; });
- a.unshift(kw);
- save(KEY.hist, JSON.stringify(a.slice(0, HIST_MAX)));
- }
- /* ---------- 搜索 ---------- */
- function buildQuery(kw) {
- return 'site:' + SITE + ' ' + kw;
- }
- function go() {
- const kw = input.value.trim();
- if (!kw) { input.focus(); return; }
- pushHist(kw);
- hideSug();
- const q = buildQuery(kw);
- const url = ENGINES[engine].url + encodeURIComponent(q);
- const w = window.open(url, '_blank');
- if (!w) location.href = url; // 弹窗被拦截时降级
- }
- goBtn.addEventListener('click', go);
- input.addEventListener('keydown', function (e) {
- if (e.key === 'Enter') {
- e.preventDefault();
- const on = sugBox.querySelector('.sug-item.on');
- if (sugBox.style.display === 'block' && on) input.value = on.dataset.q; // 回车选高亮联想词
- go();
- } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
- const items = Array.prototype.slice.call(sugBox.querySelectorAll('.sug-item'));
- if (!items.length || sugBox.style.display !== 'block') return;
- e.preventDefault();
- let idx = items.findIndex(function (n) { return n.classList.contains('on'); });
- idx = e.key === 'ArrowDown' ? Math.min(items.length - 1, idx + 1) : Math.max(0, idx - 1);
- items.forEach(function (n) { n.classList.remove('on'); });
- items[idx].classList.add('on');
- input.value = items[idx].dataset.q;
- } else if (e.key === 'Escape') {
- input.value = '';
- input.blur();
- hideSug();
- }
- });
- minBtn.addEventListener('click', function () { setMin(true); });
- openBtn.addEventListener('click', function () {
- setMin(false); input.focus();
- if (!input.value.trim()) showHistory();
- });
- select.addEventListener('change', function () { engine = select.value; save(KEY.engine, engine); });
- document.addEventListener('keydown', function (e) {
- if (e.altKey && !e.ctrlKey && !e.metaKey && e.key && e.key.toLowerCase() === HOTKEY) {
- e.preventDefault(); setMin(false); input.focus(); input.select();
- }
- });
- /* ---------- 联想词 + 历史(JSONP) ---------- */
- let sugTimer = null, sugSeq = 0;
- const sugCache = Object.create(null);
- function hideSug() { sugBox.style.display = 'none'; sugBox.innerHTML = ''; }
- function placeSug() {
- const r = input.getBoundingClientRect();
- sugBox.style.left = Math.max(8, r.left) + 'px';
- sugBox.style.top = (r.bottom + 6) + 'px';
- sugBox.style.width = Math.max(240, r.width) + 'px';
- }
- function renderItems(list, cap) {
- if (!list || !list.length) { hideSug(); return; }
- sugBox.innerHTML =
- '<div class="sug-cap">' + cap + '</div>' +
- list.map(function (q) {
- return '<div class="sug-item" data-q="' + q.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<') + '">' +
- q.replace(/&/g, '&').replace(/</g, '<') + '</div>';
- }).join('');
- placeSug();
- sugBox.style.display = 'block';
- }
- function showHistory() {
- const h = getHist();
- if (!h.length) return;
- renderItems(h, '最近搜索');
- }
- // 历史里挑出与当前输入匹配的项:先按前缀,再按包含
- function matchHist(kw) {
- if (!HIST_FIRST) return [];
- const h = getHist();
- const low = kw.toLowerCase();
- const pre = h.filter(function (q) { return String(q).toLowerCase().indexOf(low) === 0; });
- if (pre.length) return pre;
- return h.filter(function (q) { return String(q).toLowerCase().indexOf(low) !== -1; });
- }
- function fetchSug(kw) {
- if (sugCache[kw]) { renderItems(sugCache[kw], '百度联想'); return; }
- const cb = 'wysSug' + (++sugSeq) + '_' + Date.now();
- let done = false;
- window[cb] = function (data) {
- done = true;
- const list = (data && data.g || []).map(function (x) { return x.q; }).filter(Boolean).slice(0, 10);
- sugCache[kw] = list;
- if (input.value.trim() === kw && !matchHist(kw).length) renderItems(list, '百度联想'); // 防慢响应覆盖新输入 / 覆盖已命中的历史
- cleanup();
- };
- const s = document.createElement('script');
- s.src = 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&wd=' +
- encodeURIComponent(kw) + '&cb=' + cb;
- s.onerror = cleanup;
- s.onload = function () { if (!done) cleanup(); };
- function cleanup() {
- try { delete window[cb]; } catch (e) { window[cb] = undefined; }
- if (s.parentNode) s.parentNode.removeChild(s);
- }
- document.head.appendChild(s);
- }
- input.addEventListener('input', function () {
- clearTimeout(sugTimer);
- const kw = input.value.trim();
- if (!kw) { showHistory(); return; } // 清空输入 → 回到「最近搜索」
- const m = matchHist(kw); // 历史命中优先,命中就只显示历史
- if (m.length) { renderItems(m, '最近搜索'); return; }
- if (!SUGGEST) { hideSug(); return; } // 关掉联想 → 输入中不弹下拉
- sugTimer = setTimeout(function () { fetchSug(kw); }, 300);
- });
- input.addEventListener('focus', function () { if (!input.value.trim()) showHistory(); });
- sugBox.addEventListener('click', function (e) {
- const it = e.target && e.target.closest ? e.target.closest('.sug-item') : null;
- if (!it) return;
- input.value = it.dataset.q;
- hideSug();
- go();
- });
- input.addEventListener('blur', function () { setTimeout(hideSug, 200); });
- window.addEventListener('resize', function () { if (sugBox.style.display === 'block') placeSug(); });
- /* ---------- 接管站点残留的搜索入口 ---------- */
- if (HIJACK_SITE_SEARCH) {
- document.addEventListener('click', function (e) {
- const a = e.target && e.target.closest ? e.target.closest('a[href*="search.php"]') : null;
- if (!a || panel.contains(a)) return;
- e.preventDefault();
- e.stopPropagation();
- setMin(false);
- input.focus();
- input.select();
- if (!input.value.trim()) showHistory();
- }, true);
- document.addEventListener('submit', function (e) {
- const form = e.target;
- if (!form || !form.action || form.action.indexOf('search.php') === -1) return;
- const field = form.querySelector('input[name="srchtxt"], input[name="keywords"], input[name="q"], input[type="text"], input[type="search"]');
- const kw = field && field.value ? field.value.trim() : '';
- e.preventDefault();
- e.stopPropagation();
- if (!kw) { setMin(false); input.focus(); return; }
- input.value = kw;
- go();
- }, true);
- }
- }
- /* ==========================================================
- 二、结果页(百度 / 必应):把 wuyou.net 条目卡片化 + 只看站内
- ========================================================== */
- function initSerp(which) {
- const CSS = `
- .wys-hit{position:relative;border-radius:6px;box-shadow:inset 3px 0 0 #2f6fb5;}
- .wys-hit .wys-badge{display:inline-block;margin:0 0 4px;padding:0 6px;line-height:18px;border-radius:3px;
- background:#2f6fb5;color:#fff;font:11px/18px -apple-system,"Microsoft YaHei",sans-serif;vertical-align:middle;}
- body.wys-only-on .wys-other{display:none !important;}
- #wys-only{position:fixed;right:16px;bottom:16px;z-index:2147483400;height:32px;padding:0 14px;
- border:1px solid #cfdae6;border-radius:999px;background:#fff;color:#2f6fb5;cursor:pointer;
- font:12px/30px -apple-system,"Microsoft YaHei",sans-serif;box-shadow:0 3px 14px rgba(15,35,60,.18);}
- #wys-only:hover{border-color:#9dc0e0;background:#f2f8fd;}
- #wys-only[data-on="1"]{background:#2f6fb5;color:#fff;border-color:#2f6fb5;}
- `;
- const style = document.createElement('style');
- style.textContent = CSS;
- document.head.appendChild(style);
- let hitCount = 0;
- let onlyOn = false;
- const isBing = which === 'bing';
- /* 结果块:百度取 #content_left 的直接子块;必应取 #b_results 里的 li.b_algo */
- function getBlocks() {
- if (isBing) {
- return Array.prototype.slice.call(document.querySelectorAll('#b_results > li.b_algo'));
- }
- const box = document.querySelector('#content_left') || document.querySelector('#results');
- if (!box) return [];
- return Array.prototype.slice.call(box.children).filter(function (n) {
- return n.nodeType === 1 && !/^(SCRIPT|STYLE)$/.test(n.tagName);
- });
- }
- function observerTarget() {
- if (isBing) return document.querySelector('#b_results') || document.body;
- return document.querySelector('#content_left') || document.querySelector('#results') || document.body;
- }
- const DOMAIN_HIT = /^(?:https?:\/\/)?(?:[a-z0-9-]+\.)*wuyou\.net(?:[\/?#]|$)/i;
- // 百度:有机结果的跳转链接是 baidu.com/link?url=…,href 里看不到目标域名,
- // 域名只出现在「显示网址」那行(cite/.c-showurl)的**可见文本**里;
- // 另外「大家还在搜」这类聚合模块(class 含 result-op)里的搜索链接 href 带原查询串,
- // 里面可能就有 wuyou.net,按 href 判断会整块误判,所以必须排除聚合模块、且只认可见文本。
- function isHitBaidu(block) {
- if (!block || block.nodeType !== 1) return false;
- if (/result-op/.test(block.className || '')) return false;
- const as = block.querySelectorAll('a');
- for (let i = 0; i < as.length; i++) {
- const href = as[i].getAttribute('href') || '';
- if (DOMAIN_HIT.test(href)) return true; // 真·直链
- if (/wuyou\.net/i.test(as[i].textContent || '')) return true; // 显示出来的网址文本
- }
- const cites = block.querySelectorAll('cite, .c-showurl, .f13');
- for (let j = 0; j < cites.length; j++) {
- if (/wuyou\.net/i.test(cites[j].textContent || '')) return true;
- }
- return false;
- }
- // 必应:结果链接就是真实地址,直接看 href 最准;cite / .b_attribution 里也有域名文本兜底
- function isHitBing(block) {
- if (!block || block.nodeType !== 1) return false;
- const as = block.querySelectorAll('a');
- for (let i = 0; i < as.length; i++) {
- if (DOMAIN_HIT.test(as[i].getAttribute('href') || '')) return true;
- }
- const cites = block.querySelectorAll('cite, .tptt, .b_attribution');
- for (let j = 0; j < cites.length; j++) {
- if (/wuyou\.net/i.test(cites[j].textContent || '')) return true;
- }
- return false;
- }
- function scan() {
- const blocks = getBlocks();
- if (!blocks.length) return;
- hitCount = 0;
- blocks.forEach(function (b) {
- if ((isBing ? isHitBing : isHitBaidu)(b)) {
- hitCount++;
- if (!b.classList.contains('wys-hit')) {
- b.classList.add('wys-hit');
- const badge = document.createElement('span');
- badge.className = 'wys-badge';
- badge.textContent = '无忧站内';
- // 放在块内第一个可见元素之前;找不到就插到块首
- const first = b.querySelector(isBing ? 'h2' : 'h3, .c-title, .t') || b.firstChild;
- if (first && first.parentNode === b) b.insertBefore(badge, first);
- else b.insertBefore(badge, b.firstChild);
- }
- b.classList.remove('wys-other');
- } else {
- // 上一轮可能误标过(结果页异步渲染会替换节点),这里顺手撤回
- if (b.classList.contains('wys-hit')) {
- b.classList.remove('wys-hit');
- const old = b.querySelector('.wys-badge');
- if (old && old.parentNode) old.parentNode.removeChild(old);
- }
- b.classList.add('wys-other');
- }
- });
- updateBtn();
- }
- const btn = document.createElement('button');
- btn.id = 'wys-only';
- btn.type = 'button';
- btn.addEventListener('click', function () {
- onlyOn = !onlyOn;
- document.body.classList.toggle('wys-only-on', onlyOn);
- updateBtn();
- });
- function updateBtn() {
- if (!hitCount) { btn.style.display = 'none'; return; }
- btn.style.display = 'block';
- btn.dataset.on = onlyOn ? '1' : '0';
- btn.textContent = onlyOn ? '显示全部结果' : '只看无忧站内(' + hitCount + '条)';
- }
- function boot() {
- if (!document.body) { setTimeout(boot, 300); return; }
- document.body.appendChild(btn);
- scan();
- // 结果是异步/分页加载的,监听变化后重扫
- let t = null;
- const mo = new MutationObserver(function () {
- clearTimeout(t);
- t = setTimeout(scan, 600);
- });
- mo.observe(observerTarget(), { childList: true, subtree: true });
- }
- boot();
- }
- })();
复制代码
保存为A.JS 然后用油猴导入或者直接拉到油猴扩展界面自动安装。安装后在论坛右上角有个“搜”字就是扩展了。没有传图片的权限了。用必应搜索引擎的效果最好。优先采用。
想调整的话
用 Tampermonkey 编辑器打开这个脚本,顶部有一块配置:
```
const DEFAULT_ENGINE = 'baidu'; // 可改 'bing' / 'google'
const SUGGEST = true; // 百度联想词,设为 false 关掉
const HIJACK_SITE_SEARCH = true; // 接管站点自带搜索框;你是 VIP 想保留原搜索就设 false
const HIST_MAX = 8; // 搜索历史条数
const HOTKEY = 's'; // Alt+S 呼出
``` |
|