// ==UserScript== // @name 百度搜索净化 // @namespace local.baidu.cleaner // @version 0.0.6 // @description 一定程度上去除百度搜索的广告 // @match https://www.baidu.com/* // @match https://baidu.com/* // @match https://m.baidu.com/* // @match https://image.baidu.com/* // @match https://map.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 METRO_LAB_TEXT = '地铁互动实验室'; // 百度地图静态广告选择器 // 精确选择器命中时豁免面积/尺寸保护,小屏设备也能正常删除 const MAP_STATIC_AD_SELECTORS = [ '.search-item[data-stat-code="poisearch.damoce.item"]', '#message-center-panel', 'img.message-center-img', ]; // 关闭按钮识别:只保留明确的关闭符号和文字 // 刻意去掉 'X'、'x'——中文界面正文里这俩字符太常见,容易误伤 const AD_CLOSE_TEXTS = new Set(['×', '✕', '✖', '✗', '关闭', 'Close', 'close']); // 关闭按钮的完整类名(精确匹配,不用子串,避免命中 closed/closure) const AD_CLOSE_CLASSES = /^(close|btn-close|icon-close|close-btn|close-icon|ad-close)$/i; // 关闭按钮的搜索范围:只在广告面板内部,不碰 #message-center 入口 const AD_PANEL_SELECTORS = ['#message-panel']; const POLL_INTERVAL = 500; const CLEANUP_THROTTLE = 120; const DEBUG = false; // ============================================================ // 状态 // ============================================================ let pollTimer = null; let observer = null; let pendingCleanup = null; let buttonGuardTimer = 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 getClassName(el) { if (!el || el.nodeType !== 1) return ''; try { const attr = el.getAttribute ? el.getAttribute('class') : null; if (typeof attr === 'string') return attr; } catch (e) {} return (typeof el.className === 'string') ? el.className : ''; } 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; for (const el of block.querySelectorAll('span, a, div, i, em, b')) { if (!el.isConnected || el.children.length > 0) continue; if (el.closest('h1, h2, h3, h4, h5, h6')) continue; const text = normalizeText(el.textContent); if (text.length === 0 || text.length > 4) continue; if (!AD_LABEL_TEXTS.has(text)) continue; const cls = getClassName(el); 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; for (const el of block.querySelectorAll('span, div, h3, a, em, b, i')) { if (!el.isConnected || el.children.length > 0) continue; if (EXTRA_MODULE_TEXTS.has(normalizeText(el.textContent))) return true; } return false; } function sweepSearchResults() { const left = document.getElementById('content_left'); if (!left) return 0; let removed = 0; for (const block of Array.from(left.children)) { if (!block.isConnected) continue; if (isAdBlock(block) || isExtraModuleBlock(block)) { block.remove(); removed++; } } return removed; } function removeExtraModuleGlobal() { const left = document.getElementById('content_left'); if (!left || !(left.textContent || '').includes('大家还在搜')) return 0; let removed = 0; for (const el of left.querySelectorAll('span, div, h3, a, em, b, i')) { if (!el.isConnected || 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') { block.remove(); removed++; } } return removed; } function removeFreeImageEntries() { const left = document.getElementById('content_left'); if (!left || !(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 || el.children.length > 0) continue; if (normalizeText(el.textContent) !== FREE_IMAGE_TEXT) continue; const clickable = el.closest('a, button'); if (clickable && clickable.isConnected && clickable !== document.body && left.contains(clickable)) { const parent = clickable.parentElement; if (parent && parent !== document.body && parent !== left && normalizeText(parent.textContent || '') === normalizeText(clickable.textContent || '') && parent.children.length <= 1) { parent.remove(); removed++; continue; } clickable.remove(); removed++; continue; } 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; } // ============================================================ // 百度地图:核心保护 // isExact = true 时,豁免面积和尺寸检查(精确选择器已经确认是广告容器) // ============================================================ function isMapCoreControl(el, isExact) { if (!el || el === document.body || el === document.documentElement) return true; if (el.nodeType !== 1) return true; const cls = getClassName(el); const id = el.id || ''; // 地图原生控件:所有 BMap_ 前缀类名 if (/\bBMap_/.test(cls)) return true; // 地图根容器 id if (/^(map|MapHolder|maps|map_container|mapContainer|mapWrapper)$/i.test(id)) return true; // 类名含地图容器关键字 if (/map_container|mapContainer|mapHolder|mapView|map-wrapper|mapWrapper/i.test(cls)) return true; // 内部含 canvas(地图渲染层) try { if (el.querySelector && el.querySelector('canvas')) return true; } catch (e) {} // 内部含地图核心容器/控件 try { if (el.querySelector && el.querySelector('#maps, #MapHolder, .BMap_cpyCtrl, .BMap_mask')) return true; } catch (e) {} // 面积/尺寸保护:仅对非精确选择器生效 if (!isExact) { const rect = el.getBoundingClientRect ? el.getBoundingClientRect() : null; if (rect) { if (rect.width <= 0 || rect.height <= 0) return true; const area = rect.width * rect.height; const viewArea = window.innerWidth * window.innerHeight; if (viewArea > 0 && area / viewArea > 0.3) return true; } } return false; } function isParentSharedWithMapTools(el) { const parent = el.parentElement; if (!parent || parent === document.body) return false; try { if (parent.querySelector('#maps') || parent.querySelector('#MapHolder')) return true; } catch (e) {} const pcls = getClassName(parent); if (/\bBMap_/.test(pcls) || /map_container|mapHolder|mapView/i.test(pcls)) return true; return false; } // ============================================================ // 关闭按钮识别(严格版) // ============================================================ function isCloseButton(el) { if (!el || el.nodeType !== 1) return false; if (el.children.length > 0) return false; const text = normalizeText(el.textContent); if (AD_CLOSE_TEXTS.has(text)) return true; const cls = getClassName(el); if (cls) { const parts = cls.trim().split(/\s+/).filter(Boolean); if (parts.some(c => AD_CLOSE_CLASSES.test(c))) return true; } const aria = el.getAttribute ? (el.getAttribute('aria-label') || '') : ''; if (/^(关闭|close)$/i.test(aria.trim())) return true; const title = el.getAttribute ? (el.getAttribute('title') || '') : ''; if (/^(关闭|close)$/i.test(title.trim())) return true; return false; } // ============================================================ // 删除广告面板的关闭按钮 // 修复点: // 1. 只搜 #message-panel,不碰 #message-center 入口 // 2. clickable 必须 panel.contains(clickable),防止 closest 穿出面板边界 // ============================================================ function removeAdCloseButton() { let removed = 0; for (const panelSel of AD_PANEL_SELECTORS) { for (const panel of safeQueryAll(document, panelSel)) { if (!panel.isConnected) continue; if (isMapCoreControl(panel, false)) continue; for (const el of panel.querySelectorAll('span, i, em, b, a, div, button, label')) { if (!el.isConnected) continue; if (!isCloseButton(el)) continue; if (isMapCoreControl(el, false)) continue; const clickable = el.closest('a, button, [role="button"]'); // 关键边界:clickable 必须在当前 panel 内部 if (clickable && clickable.isConnected && clickable !== panel && clickable !== document.body && panel.contains(clickable) && !isMapCoreControl(clickable, false)) { clickable.remove(); removed++; log('删除关闭按钮(可点击父级):', panelSel); continue; } const parent = el.parentElement; if (parent && parent !== panel && parent !== document.body && parent.children.length === 1 && panel.contains(parent) && !isMapCoreControl(parent, false)) { parent.remove(); } else { el.remove(); } removed++; log('删除关闭按钮(叶子/包装):', panelSel); } } } return removed; } // ============================================================ // 广告面板删除后留下的空壳 // 修复点:不删除 #message-panel,只设为 display:none // 这样消息中心入口的 JS 逻辑不受影响,只是视觉上不再留空白 // ============================================================ function hideEmptyMessagePanel() { let removed = 0; for (const panel of safeQueryAll(document, '#message-panel')) { if (!panel.isConnected) continue; if (isMapCoreControl(panel, true)) continue; // 广告面板还在 → 有内容,不动 if (panel.querySelector('#message-center-panel')) continue; // 有图片 → 有内容,不动 if (panel.querySelector('img')) continue; // 有可点击元素 → 有正常内容,不动 if (panel.querySelector('a, button, [role="button"]')) continue; // 文本量超过 3 → 有正常内容,不动 if (normalizeText(panel.textContent || '').length > 3) continue; // 满足“空壳”条件:只隐藏,不删除 try { panel.style.setProperty('display', 'none', 'important'); removed++; log('隐藏空壳消息面板'); } catch (e) {} } return removed; } // ============================================================ // 百度地图:总清理 // ============================================================ function cleanMapPage() { let removed = 0; // 1. “地铁互动实验室”按钮 for (const el of document.querySelectorAll('span, a, div, button, em, b, i, p, label')) { if (!el.isConnected || el.children.length > 0) continue; if (normalizeText(el.textContent) !== METRO_LAB_TEXT) continue; if (isMapCoreControl(el, false) || isParentSharedWithMapTools(el)) continue; const clickable = el.closest('a, button, [role="button"]'); if (clickable && clickable.isConnected && clickable !== document.body && !isMapCoreControl(clickable, false)) { clickable.remove(); removed++; continue; } if (!isMapCoreControl(el, false)) { el.remove(); removed++; } } // 2. 精确广告选择器(isExact = true,豁免面积/尺寸保护) for (const sel of MAP_STATIC_AD_SELECTORS) { for (const el of safeQueryAll(document, sel)) { if (!el.isConnected) continue; if (isMapCoreControl(el, true)) { log('保护拦截(自身,BMap/canvas):', sel); continue; } if (isParentSharedWithMapTools(el)) { log('保护拦截(兄弟节点):', sel); continue; } el.remove(); removed++; log('地图广告删除:', sel); } } // 3. 广告面板的关闭按钮(×) removed += removeAdCloseButton(); // 4. 关闭按钮删除后留下的空壳面板(只隐藏,不删除) removed += hideEmptyMessagePanel(); return removed; } // ============================================================ // 统一清理入口 // ============================================================ function runCleanup() { try { const host = location.hostname; const isMap = host === 'map.baidu.com'; const isSearchLike = /(^|\.)baidu\.com$/.test(host) && !isMap; let total = 0; if (isMap) total += cleanMapPage(); if (isSearchLike || host === 'image.baidu.com') { total += sweepSearchResults(); total += removeExtraModuleGlobal(); total += removeFreeImageEntries(); total += removeRightSidebar(); } if (total > 0) log('本轮清理:', total); } 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'; let buttonClickHandler = null; function ensureButton() { 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'); if (!buttonClickHandler) { buttonClickHandler = (e) => { e.preventDefault(); e.stopPropagation(); runCleanup(); const b = document.getElementById(BUTTON_ID); if (b) { b.textContent = '已清理'; setTimeout(() => { const bb = document.getElementById(BUTTON_ID); if (bb) bb.textContent = '去广告'; }, 1200); } }; } btn.onclick = buttonClickHandler; (document.body || document.documentElement).appendChild(btn); } function startButtonGuard() { if (buttonGuardTimer) return; buttonGuardTimer = setInterval(ensureButton, 800); ensureButton(); } // ============================================================ // 启动 // ============================================================ function boot() { runCleanup(); startPolling(); startObserver(); startButtonGuard(); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot); } else { boot(); } })();