// ==UserScript== // @name 百度搜索净化 // @namespace local.baidu.cleaner // @version 0.0.6.5 // @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 = '地铁互动实验室'; // 百度地图静态广告选择器 // #message-center-panel 是右上角消息中心弹出的广告面板(用户实测捕获,363x210) // img.message-center-img 是面板内的广告图,作为兜底 const MAP_STATIC_AD_SELECTORS = [ '.search-item[data-stat-code="poisearch.damoce.item"]', '#message-center-panel', 'img.message-center-img', ]; 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 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 = (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; 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) { const parent = clickable.parentElement; if (parent && parent !== document.body) { if (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; } // ============================================================ // 百度地图:核心保护 // ============================================================ function isMapCoreControl(el) { if (!el || el === document.body || el === document.documentElement) return true; if (el.nodeType !== 1) return true; const cls = (typeof el.className === 'string') ? el.className : ''; const id = el.id || ''; if (/\bBMap_/.test(cls)) return true; 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; 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) {} 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 = (typeof parent.className === 'string') ? parent.className : ''; if (/\bBMap_/.test(pcls) || /map_container|mapHolder|mapView/i.test(pcls)) return true; return false; } // ============================================================ // 百度地图:广告清理 // ============================================================ 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) || isParentSharedWithMapTools(el)) continue; const clickable = el.closest('a, button, [role="button"]'); if (clickable && clickable.isConnected && clickable !== document.body && !isMapCoreControl(clickable)) { clickable.remove(); removed++; continue; } if (!isMapCoreControl(el)) { el.remove(); removed++; } } // 2. 精确广告选择器(EasyList + 用户捕获的 #message-center-panel) for (const sel of MAP_STATIC_AD_SELECTORS) { for (const el of safeQueryAll(document, sel)) { if (!el.isConnected) continue; if (isMapCoreControl(el)) { log('保护拦截(自身):', sel); continue; } if (isParentSharedWithMapTools(el)) { log('保护拦截(兄弟节点):', sel); continue; } el.remove(); removed++; log('地图广告删除:', sel); } } 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(); } })();