// ==UserScript== // @name 百度搜索净化 // @namespace local.baidu.cleaner // @version 0.0.5 // @description 一定程度上去除百度搜索的广告 // @match https://www.baidu.com/* // @match https://baidu.com/* // @match https://m.baidu.com/* // @match https://image.baidu.com/* // @run-at document-idle // @grant none // @license GPL-3.0 // ==/UserScript== (function () { 'use strict'; // ============================================================ // 配置 // ============================================================ const AD_MARKERS = [ '[data-tuiguang]', '[data-click*="tuiguang"]', '.ec-tuiguang', '.c-icon-bear-p', '[data-lp][data-placeid]', '.EC_result', '.ecom-result', '.ec_wise_ad', '[data-cmatchid]', ]; const RIGHT_SIDEBAR = [ '#content_right', '.s-hotsearch-wrapper', ]; const EXTRA_MODULE_SELECTORS = [ '#rs', '.rs_new', ]; const EXTRA_MODULE_TEXTS = new Set(['大家还在搜']); const FREE_IMAGE_TEXT = '免费生图'; const AD_LABEL_TEXTS = new Set(['广告', '推广', '商业推广']); const POLL_INTERVAL = 500; // 轮询周期 const CLEANUP_THROTTLE = 120; // 观察器触发的清理节流 const DEBUG = false; // ============================================================ // 状态 // ============================================================ let pollTimer = null; let observer = null; let pendingCleanup = null; // ============================================================ // 工具 // ============================================================ function safeQueryAll(root, selector) { try { return root.querySelectorAll(selector); } catch (e) { return []; } } function matchesAny(el, selectors) { for (const sel of selectors) { try { if (el.matches(sel)) return true; } catch (e) {} } return false; } function containsAny(root, selectors) { for (const sel of selectors) { try { if (root.querySelector(sel)) return true; } catch (e) {} } return false; } function normalizeText(t) { return (t || '').replace(/[\s\u200b\u200c\u200d\u00a0\ufeff]/g, ''); } function log(...args) { if (DEBUG) console.log('[百度净化]', ...args); } function findResultBlock(el) { let cur = el; let depth = 0; while (cur && cur !== document.body && depth < 8) { if (cur.id === 'content_left') return null; if (cur.parentElement && cur.parentElement.id === 'content_left') return cur; if (cur.classList && cur.classList.contains('c-container')) return cur; cur = cur.parentElement; depth++; } return null; } // ============================================================ // 广告块判定 // ============================================================ function isAdBlock(block) { if (matchesAny(block, AD_MARKERS)) return true; if (containsAny(block, AD_MARKERS)) return true; const candidates = block.querySelectorAll('span, a, div, i, em, b'); for (const el of candidates) { if (!el.isConnected) continue; if (el.children.length > 0) continue; if (el.closest('h1, h2, h3, h4, h5, h6')) continue; // 先归一化再判断长度,避免零宽字符把“广告”撑到 5 个字符 const text = normalizeText(el.textContent); if (text.length === 0 || text.length > 4) continue; if (!AD_LABEL_TEXTS.has(text)) continue; const cls = (typeof el.className === 'string') ? el.className : ''; if (/gray|blue|label|tag|badge|tuig/i.test(cls)) return true; let fontSize = 0; try { fontSize = parseFloat(window.getComputedStyle(el).fontSize) || 0; } catch (e) {} if (fontSize > 0 && fontSize <= 15) return true; } return false; } // ============================================================ // “大家还在搜”等模块判定 // ============================================================ function isExtraModuleBlock(block) { if (matchesAny(block, EXTRA_MODULE_SELECTORS)) return true; if (containsAny(block, EXTRA_MODULE_SELECTORS)) return true; const candidates = block.querySelectorAll('span, div, h3, a, em, b, i'); for (const el of candidates) { if (!el.isConnected) continue; if (el.children.length > 0) continue; if (EXTRA_MODULE_TEXTS.has(normalizeText(el.textContent))) return true; } return false; } // ============================================================ // 扫描结果区(#content_left 直接子块) // ============================================================ function sweepResults() { const left = document.getElementById('content_left'); if (!left) return 0; let removed = 0; const blocks = Array.from(left.children); for (const block of blocks) { if (!block.isConnected) continue; if (isAdBlock(block) || isExtraModuleBlock(block)) { log('删除结果块:', block, '预览:', (block.textContent || '').slice(0, 60)); block.remove(); removed++; } } return removed; } // 全局兜底:额外模块嵌在组合块里时使用 function removeExtraModuleGlobal() { const left = document.getElementById('content_left'); if (!left) return 0; if (!(left.textContent || '').includes('大家还在搜')) return 0; let removed = 0; for (const el of left.querySelectorAll('span, div, h3, a, em, b, i')) { if (!el.isConnected) continue; if (el.children.length > 0) continue; if (!EXTRA_MODULE_TEXTS.has(normalizeText(el.textContent))) continue; const block = findResultBlock(el); if (block && block.isConnected && block.id !== 'content_left') { log('全局扫描删除模块:', block); block.remove(); removed++; } } return removed; } // ============================================================ // 免费生图入口删除 // 修复点:只删交互元素(a/button)及其空包装层, // 不再依据“文本量小于阈值”整卡删除,避免误删旁边的正常图片。 // ============================================================ function removeFreeImageEntries() { const left = document.getElementById('content_left'); if (!left) return 0; // 快速路径:整片结果区没有这个词直接跳过 if (!(left.textContent || '').includes(FREE_IMAGE_TEXT)) return 0; let removed = 0; for (const el of left.querySelectorAll('span, a, div, em, b, i, p')) { if (!el.isConnected) continue; if (el.children.length > 0) continue; if (normalizeText(el.textContent) !== FREE_IMAGE_TEXT) continue; const clickable = el.closest('a, button'); if (clickable && clickable !== left && clickable.isConnected) { const parent = clickable.parentElement; // 包装层里只有这一个交互元素,且文本也就是它,说明是纯入口框,连包装一起删 if (parent && parent !== left && parent !== document.body) { const parentText = normalizeText(parent.textContent || ''); const clickText = normalizeText(clickable.textContent || ''); if (parentText === clickText && parent.children.length <= 1) { log('删除免费生图包装层:', parent); parent.remove(); removed++; continue; } } log('删除免费生图入口:', clickable); clickable.remove(); removed++; continue; } log('删除免费生图叶子元素:', el); el.remove(); removed++; } return removed; } // ============================================================ // 右侧栏 // ============================================================ function removeRightSidebar() { let removed = 0; for (const sel of RIGHT_SIDEBAR) { for (const el of safeQueryAll(document, sel)) { if (el.isConnected) { el.remove(); removed++; } } } return removed; } // ============================================================ // 清理入口 // ============================================================ function runCleanup() { try { const a = sweepResults(); const b = removeExtraModuleGlobal(); const c = removeFreeImageEntries(); const d = removeRightSidebar(); if (a || b || c || d) { log(`结果块 ${a},全局模块 ${b},免费生图 ${c},右侧 ${d}`); } } catch (e) { if (DEBUG) console.warn('[百度净化] cleanup 异常', e); } } function scheduleCleanup() { if (pendingCleanup) return; pendingCleanup = setTimeout(() => { pendingCleanup = null; runCleanup(); }, CLEANUP_THROTTLE); } // ============================================================ // 轮询与观察器 // ============================================================ function startPolling() { if (pollTimer) return; pollTimer = setInterval(runCleanup, POLL_INTERVAL); } function startObserver() { if (observer) observer.disconnect(); observer = new MutationObserver(scheduleCleanup); const target = document.getElementById('content_left') || document.body || document.documentElement; if (target) { observer.observe(target, { childList: true, subtree: true }); } } // ============================================================ // 手动按钮 // ============================================================ const BUTTON_ID = 'baidu-cleaner-btn'; function createManualButton() { if (document.getElementById(BUTTON_ID)) return; const btn = document.createElement('button'); btn.id = BUTTON_ID; btn.textContent = '去广告'; btn.style.cssText = 'position:fixed;bottom:24px;right:24px;z-index:2147483647;' + 'padding:10px 16px;background:#1769aa;color:#fff;border:none;' + 'border-radius:20px;font-size:14px;cursor:pointer;' + 'box-shadow:0 2px 8px rgba(0,0,0,.3);opacity:.9;'; btn.onmouseenter = () => (btn.style.opacity = '1'); btn.onmouseleave = () => (btn.style.opacity = '.9'); btn.onclick = (e) => { e.preventDefault(); e.stopPropagation(); runCleanup(); btn.textContent = '已清理'; setTimeout(() => (btn.textContent = '去广告'), 1200); }; (document.body || document.documentElement).appendChild(btn); } // ============================================================ // 启动 // ============================================================ function boot() { runCleanup(); startPolling(); startObserver(); createManualButton(); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot); } else { boot(); } })();