// ==UserScript== // @name 小说漫画网页广告拦截器 // @namespace http://tampermonkey.net/ // @version 4.9.4 // @author DeepSeek&Gemini // @description 一个手机端via浏览器能用的强大的广告拦截器 // @match *://*/* // @license MIT // @grant unsafeWindow // @grant GM_setValue // @grant GM_getValue // @grant GM_registerMenuCommand // @grant GM_notification // @run-at document-start // ==/UserScript== (function() { 'use strict'; const CONFIG = { Z_INDEX: 2147483647, CACHE_TTL: 300000, BATCH_SIZE: 20, LOG_MAX: 200, LOG_IDENTIFIER_TTL: 300000, STRONG_BLOCK_TIMEOUT: 600000, DEBOUNCE_WAIT: 100, THROTTLE_LIMIT: 100, URL_DYNAMIC_PATTERNS: [ /\?.*[tT]=/, /\?.*timestamp/, /\?.*rand/, /\?.*rnd/, /\?.*[0-9]{13,}/, /\?.*\d{10,}/, /\/\d{10,}\./, /\/[0-9a-f]{32,}\./ ] }; const _globals = (typeof unsafeWindow !== 'undefined' ? unsafeWindow : window); const _document = _globals.document; const _location = _globals.location; const _MutationObserver = _globals.MutationObserver; const _Element = _globals.Element; const _setTimeout = _globals.setTimeout; const _clearTimeout = _globals.clearTimeout; const _requestAnimationFrame = _globals.requestAnimationFrame; const _cancelAnimationFrame = _globals.cancelAnimationFrame; const _XMLHttpRequest = _globals.XMLHttpRequest; const _fetch = _globals.fetch; const _Proxy = _globals.Proxy; const _Set = _globals.Set; const _Map = _globals.Map; function escapeHtml(unsafe) { if (unsafe == null) return ''; return String(unsafe) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } if (_document.designMode === 'on' || _document.documentElement.style.pointerEvents === 'none') { _document.designMode = 'off'; _document.documentElement.style.pointerEvents = ''; } if (_globals._adblock_original_beforeunload) { _globals.onbeforeunload = _globals._adblock_original_beforeunload; delete _globals._adblock_original_beforeunload; } else { _globals.onbeforeunload = null; } _globals._adblock_strongBlockingActive = false; delete _globals._adblock_original_designMode; delete _globals._adblock_original_pointerEvents; let panelOpenCount = 0; let strongBlockingEnabled = false; let blockingTimer = null; function enableStrongBlocking() { if (strongBlockingEnabled) return; _globals._adblock_original_beforeunload = _globals.onbeforeunload; _globals.onbeforeunload = function(e) { e.preventDefault(); e.returnValue = '系统可能不会保存您所做的更改。'; return '系统可能不会保存您所做的更改。'; }; strongBlockingEnabled = true; _globals._adblock_strongBlockingActive = true; if (blockingTimer) _clearTimeout(blockingTimer); blockingTimer = _setTimeout(() => { if (panelOpenCount > 0) { panelOpenCount = 0; disableStrongBlocking(); } }, CONFIG.STRONG_BLOCK_TIMEOUT); } function disableStrongBlocking() { if (!strongBlockingEnabled) return; _globals.onbeforeunload = _globals._adblock_original_beforeunload || null; delete _globals._adblock_original_beforeunload; delete _globals._adblock_original_designMode; delete _globals._adblock_original_pointerEvents; strongBlockingEnabled = false; _globals._adblock_strongBlockingActive = false; if (blockingTimer) { _clearTimeout(blockingTimer); blockingTimer = null; } } function setupNavigationBlocking() { panelOpenCount++; if (panelOpenCount === 1) { enableStrongBlocking(); if (currentConfig.modules.blockDynamicScripts) { DynamicScriptInterceptor.disable(); } } } function teardownNavigationBlocking() { panelOpenCount--; if (panelOpenCount === 0) { disableStrongBlocking(); if (currentConfig.modules.blockDynamicScripts) { DynamicScriptInterceptor.enable(); } } } const DEFAULT_MODULE_STATE = { removeInlineScripts: false, removeExternalScripts: false, interceptThirdParty: false, blockDynamicScripts: false, manageCSP: false, scriptBlacklistMode: false }; const MODULE_NAMES = { removeInlineScripts: '移除内嵌脚本', removeExternalScripts: '移除外联脚本', blockDynamicScripts: '拦截动态脚本', interceptThirdParty: '拦截第三方资源', manageCSP: 'CSP策略管理', scriptBlacklistMode: '脚本黑名单模式' }; const DEFAULT_CSP_RULES_TEMPLATE = [ { id: 1, name: '只允许同源外部脚本', rule: "script-src 'none'", enabled: false }, { id: 2, name: '只允许同源外部样式', rule: "style-src 'none'", enabled: false }, { id: 3, name: '只允许同源图片', rule: "img-src 'none'", enabled: false }, { id: 4, name: '禁止所有框架', rule: "frame-src 'none'", enabled: false }, { id: 5, name: '禁止所有媒体', rule: "media-src 'none'", enabled: false }, { id: 6, name: '禁止所有对象与嵌入', rule: "object-src 'none'", enabled: false } ]; let currentConfig = { modules: { ...DEFAULT_MODULE_STATE }, cspRules: DEFAULT_CSP_RULES_TEMPLATE.map(rule => ({ ...rule })), whitelist: new Set(), keywordWhitelist: new Set(), thirdPartySettings: {}, scriptBlacklist: new Set(), thirdPartyWhitelist: [], inlineScriptStrictMode: undefined }; const StorageManager = { getConfigKey(domain) { return `adblock_unified_config_${domain}`; }, loadConfig() { const hostname = _location.hostname; const key = this.getConfigKey(hostname); try { const saved = GM_getValue(key, null); if (saved) { const data = JSON.parse(saved); if (data.modules) Object.assign(currentConfig.modules, data.modules); if (data.cspRules) currentConfig.cspRules = data.cspRules.map(r => ({ ...r })); if (Array.isArray(data.whitelist)) currentConfig.whitelist = new Set(data.whitelist); if (Array.isArray(data.keywordWhitelist)) currentConfig.keywordWhitelist = new Set(data.keywordWhitelist); if (data.thirdPartySettings && typeof data.thirdPartySettings === 'object') { currentConfig.thirdPartySettings = data.thirdPartySettings; } if (Array.isArray(data.scriptBlacklist)) currentConfig.scriptBlacklist = new Set(data.scriptBlacklist); if (Array.isArray(data.thirdPartyWhitelist)) currentConfig.thirdPartyWhitelist = data.thirdPartyWhitelist; if (data.inlineScriptStrictMode !== undefined) currentConfig.inlineScriptStrictMode = data.inlineScriptStrictMode; } } catch (e) {} if (!currentConfig.thirdPartySettings) currentConfig.thirdPartySettings = {}; if (!currentConfig.thirdPartyWhitelist) currentConfig.thirdPartyWhitelist = []; }, saveConfig() { const hostname = _location.hostname; const key = this.getConfigKey(hostname); const toStore = { modules: currentConfig.modules, cspRules: currentConfig.cspRules, whitelist: Array.from(currentConfig.whitelist), keywordWhitelist: Array.from(currentConfig.keywordWhitelist), thirdPartySettings: currentConfig.thirdPartySettings, scriptBlacklist: Array.from(currentConfig.scriptBlacklist), thirdPartyWhitelist: currentConfig.thirdPartyWhitelist, inlineScriptStrictMode: currentConfig.inlineScriptStrictMode }; GM_setValue(key, JSON.stringify(toStore)); }, resetAllSettings() { currentConfig.modules = { ...DEFAULT_MODULE_STATE }; currentConfig.cspRules = DEFAULT_CSP_RULES_TEMPLATE.map(rule => ({ ...rule })); currentConfig.whitelist.clear(); currentConfig.keywordWhitelist.clear(); currentConfig.thirdPartySettings = {}; currentConfig.scriptBlacklist.clear(); currentConfig.thirdPartyWhitelist = []; currentConfig.inlineScriptStrictMode = undefined; this.saveConfig(); } }; class LRUCache { constructor(capacity = 100, defaultTTL = 0) { this.capacity = capacity; this.defaultTTL = defaultTTL; this.cache = new _Map(); } get(key) { if (!this.cache.has(key)) return null; const entry = this.cache.get(key); const ttl = entry.ttl !== undefined ? entry.ttl : this.defaultTTL; if (ttl > 0 && (Date.now() - entry.timestamp) > ttl) { this.cache.delete(key); return null; } this.cache.delete(key); this.cache.set(key, entry); return entry.value; } set(key, value, ttl) { const finalTTL = ttl !== undefined ? ttl : this.defaultTTL; const entry = { value, timestamp: Date.now(), ttl: finalTTL }; if (this.cache.has(key)) { this.cache.delete(key); } else if (this.cache.size >= this.capacity) { const firstKey = this.cache.keys().next().value; this.cache.delete(firstKey); } this.cache.set(key, entry); } has(key) { const entry = this.cache.get(key); if (!entry) return false; const ttl = entry.ttl !== undefined ? entry.ttl : this.defaultTTL; if (ttl > 0 && (Date.now() - entry.timestamp) > ttl) { this.cache.delete(key); return false; } return true; } delete(key) { return this.cache.delete(key); } clear() { this.cache.clear(); } get size() { return this.cache.size; } } class URLResolutionCache { constructor() { this.hostnameCache = new LRUCache(1000, CONFIG.CACHE_TTL); this.domainCache = new LRUCache(1000, CONFIG.CACHE_TTL); this.absoluteUrlCache = new LRUCache(1000, CONFIG.CACHE_TTL); this.thirdPartyCache = new LRUCache(1000, CONFIG.CACHE_TTL); this.whitelistCache = new LRUCache(500, CONFIG.CACHE_TTL); this.urlCheckCache = new LRUCache(500, CONFIG.CACHE_TTL); } isDynamicURL(url) { if (!url || typeof url !== 'string') return false; const cacheKey = `dynamic_${url}`; if (this.urlCheckCache.has(cacheKey)) return this.urlCheckCache.get(cacheKey); const result = CONFIG.URL_DYNAMIC_PATTERNS.some(pattern => pattern.test(url)); this.urlCheckCache.set(cacheKey, result, CONFIG.CACHE_TTL); return result; } getHostname(url) { if (!url || typeof url !== 'string') return null; const cacheKey = `hostname_${url}`; if (this.hostnameCache.has(cacheKey)) return this.hostnameCache.get(cacheKey); if (url.startsWith('data:') || url.startsWith('blob:') || url.startsWith('about:blank')) { this.hostnameCache.set(cacheKey, null, 60000); return null; } try { const hostname = new URL(url, _location.href).hostname; const ttl = this.isDynamicURL(url) ? 30000 : CONFIG.CACHE_TTL; this.hostnameCache.set(cacheKey, hostname, ttl); return hostname; } catch (e) { this.hostnameCache.set(cacheKey, null, 30000); return null; } } getDomain(hostname) { if (!hostname) return null; const cacheKey = `domain_${hostname}`; if (this.domainCache.has(cacheKey)) return this.domainCache.get(cacheKey); const parts = hostname.split('.'); const domain = parts.length <= 2 ? hostname : parts.slice(-2).join('.'); this.domainCache.set(cacheKey, domain, CONFIG.CACHE_TTL); return domain; } getAbsoluteURL(url) { if (!url) return ''; const cacheKey = `absolute_${url}_${_location.href}`; if (this.absoluteUrlCache.has(cacheKey)) return this.absoluteUrlCache.get(cacheKey); try { const absoluteUrl = new URL(url, _location.href).href; const ttl = this.isDynamicURL(url) ? 30000 : CONFIG.CACHE_TTL; this.absoluteUrlCache.set(cacheKey, absoluteUrl, ttl); return absoluteUrl; } catch (e) { this.absoluteUrlCache.set(cacheKey, url, 30000); return url; } } isThirdPartyHost(resourceHostname, currentHost, blockParentSubDomains = true) { if (!resourceHostname) return false; const cacheKey = `thirdparty_${resourceHostname}_${currentHost}_${blockParentSubDomains}`; if (this.thirdPartyCache.has(cacheKey)) return this.thirdPartyCache.get(cacheKey); let isThirdParty = false; if (!currentHost || !resourceHostname) { isThirdParty = false; } else if (resourceHostname === currentHost) { isThirdParty = false; } else if (blockParentSubDomains) { isThirdParty = true; } else { const currentParts = currentHost.split('.'); const resourceParts = resourceHostname.split('.'); if (currentParts.length >= 2 && resourceParts.length >= 2) { const currentMainDomain = currentParts.slice(-2).join('.'); const resourceMainDomain = resourceParts.slice(-2).join('.'); isThirdParty = currentMainDomain !== resourceMainDomain; } else { isThirdParty = resourceHostname !== currentHost; } } this.thirdPartyCache.set(cacheKey, isThirdParty, CONFIG.CACHE_TTL); return isThirdParty; } isWhitelisted(url, thirdPartyWhitelist) { if (!url || !thirdPartyWhitelist) return false; const cacheKey = `whitelist_${url}_${_location.hostname}`; if (this.whitelistCache.has(cacheKey)) return this.whitelistCache.get(cacheKey); let isWhitelisted = false; for (const pattern of thirdPartyWhitelist) { try { if (pattern.includes('://')) { if (url.includes(pattern)) { isWhitelisted = true; break; } } else { const urlHost = new URL(url, _location.href).hostname; const patternHost = pattern.startsWith('*.') ? pattern.substring(2) : pattern; if (urlHost.includes(patternHost) || url.includes(patternHost)) { isWhitelisted = true; break; } } } catch (e) { if (url.includes(pattern)) { isWhitelisted = true; break; } } } this.whitelistCache.set(cacheKey, isWhitelisted, CONFIG.CACHE_TTL); return isWhitelisted; } clear() { this.hostnameCache.clear(); this.domainCache.clear(); this.absoluteUrlCache.clear(); this.thirdPartyCache.clear(); this.whitelistCache.clear(); this.urlCheckCache.clear(); } } const urlCache = new URLResolutionCache(); const Utils = { truncateString(str, maxLength = 200) { if (typeof str !== 'string') return ''; if (str.length <= maxLength) return str; return str.slice(0, maxLength) + '...'; }, getCurrentHostname() { return _location.hostname; }, isElement(el) { return el instanceof _Element; }, getScriptContentPreview(scriptElement) { if (!scriptElement || scriptElement.tagName !== 'SCRIPT') return ''; return this.truncateString(scriptElement.textContent, 200); }, getIframeSrcPreview(iframeElement) { if (!iframeElement || iframeElement.tagName !== 'IFRAME') return ''; return this.truncateString(iframeElement.src, 200); }, getResourceHostname(url) { return urlCache.getHostname(url); }, getDomain(hostname) { return urlCache.getDomain(hostname); }, isThirdPartyHost(resourceHostname, currentHost, blockParentSubDomains = true) { return urlCache.isThirdPartyHost(resourceHostname, currentHost, blockParentSubDomains); }, getAbsoluteURL(url) { return urlCache.getAbsoluteURL(url); }, getContentIdentifier(element, reasonType = null) { if (!element && !reasonType) return null; if (element && this.isElement(element)) { const tagName = element.tagName; const src = element.src || element.getAttribute('data-src') || element.href || element.action || ''; if (tagName === 'SCRIPT') { return element.src ? `SCRIPT_SRC: ${this.truncateString(element.src, 150)}` : `SCRIPT_CONTENT: ${this.getScriptContentPreview(element)}`; } else if (tagName === 'IFRAME') { return `IFRAME_SRC: ${this.truncateString(element.src, 150)}`; } else if (tagName === 'IMG') { return src ? `IMG_SRC: ${this.truncateString(src, 150)}` : null; } else if (tagName === 'A') { return src ? `A_HREF: ${this.truncateString(src, 150)}` : null; } else if (tagName === 'LINK' && element.rel === 'stylesheet' && element.href) { return `CSS_HREF: ${this.truncateString(element.href, 150)}`; } else if (tagName === 'STYLE') { return `STYLE_CONTENT: ${this.truncateString(element.textContent, 150)}`; } else if (tagName === 'EMBED') { return src ? `EMBED_SRC: ${this.truncateString(src, 150)}` : null; } else if (tagName === 'OBJECT') { return src ? `OBJECT_DATA: ${this.truncateString(src, 150)}` : null; } return null; } else if (reasonType && typeof reasonType.detail === 'string') { if (reasonType.detail.startsWith('SRC:')) { return `${reasonType.type || 'INTERCEPTED'}_SRC: ${this.truncateString(reasonType.detail.substring(4).trim(), 150)}`; } else if (reasonType.detail.startsWith('URL:')) { return `${reasonType.type || 'INTERCEPTED'}_URL: ${this.truncateString(reasonType.detail.substring(5).trim(), 150)}`; } else if (reasonType.type === 'EVAL') { return `EVAL_CODE: ${this.truncateString(reasonType.detail, 150)}`; } else if (reasonType.type === 'FUNCTION_CONSTRUCTOR') { return `FUNCTION_CODE: ${this.truncateString(reasonType.detail, 150)}`; } else if (reasonType.type === 'DOCUMENT_WRITE') { return `DOCUMENT_WRITE: ${this.truncateString(reasonType.detail, 150)}`; } else if (reasonType.type === 'SETTIMEOUT') { return `SETTIMEOUT: ${this.truncateString(reasonType.detail, 150)}`; } else if (reasonType.type === 'SETINTERVAL') { return `SETINTERVAL: ${this.truncateString(reasonType.detail, 150)}`; } else if (reasonType.type === 'REQUESTANIMATIONFRAME') { return `REQUESTANIMATIONFRAME: ${this.truncateString(reasonType.detail, 150)}`; } else if (reasonType.type === 'THIRD_PARTY') { return `THIRD_PARTY: ${this.truncateString(reasonType.detail, 150)}`; } else if (reasonType.type === 'SCRIPT_BLACKLIST') { return `BLACKLIST: ${this.truncateString(reasonType.detail, 150)}`; } else if (reasonType.type === '内联事件') { return `INLINE_EVENT: ${this.truncateString(reasonType.detail, 150)}`; } else if (reasonType.type === 'javascript URL') { return `JAVASCRIPT_URL: ${this.truncateString(reasonType.detail, 150)}`; } return `LOG_DETAIL: ${this.truncateString(reasonType.detail, 150)}`; } return null; }, isParentProcessed(element) { let parent = element.parentElement; while (parent) { if (parent.dataset.adblockProcessed === 'true' || ProcessedElementsCache.isProcessed(parent)) return true; parent = parent.parentElement; } return false; }, debounce(func, wait = CONFIG.DEBOUNCE_WAIT) { let timeout; return function(...args) { _clearTimeout(timeout); timeout = _setTimeout(() => func.apply(this, args), wait); }; }, throttle(func, limit = CONFIG.THROTTLE_LIMIT) { let inThrottle; return function(...args) { if (!inThrottle) { func.apply(this, args); inThrottle = true; _setTimeout(() => inThrottle = false, limit); } }; }, isThirdParty(url, blockParentSubDomains = true) { if (!url) return false; const cacheKey = `isThirdParty_${url}_${_location.hostname}_${blockParentSubDomains}`; if (urlCache.urlCheckCache.has(cacheKey)) return urlCache.urlCheckCache.get(cacheKey); try { const urlObj = new URL(url, _location.href); const hostname = urlObj.hostname; if (!hostname || url.startsWith('data:') || url.startsWith('blob:')) { urlCache.urlCheckCache.set(cacheKey, false, CONFIG.CACHE_TTL); return false; } const result = urlCache.isThirdPartyHost(hostname, this.getCurrentHostname(), blockParentSubDomains); urlCache.urlCheckCache.set(cacheKey, result, CONFIG.CACHE_TTL); return result; } catch (e) { const currentHost = this.getCurrentHostname(); const currentParts = currentHost.split('.'); const urlStr = url.toLowerCase(); if (!urlStr.includes('://') || urlStr.startsWith('/')) { urlCache.urlCheckCache.set(cacheKey, false, CONFIG.CACHE_TTL); return false; } if (blockParentSubDomains) { const result = !urlStr.includes(currentHost); urlCache.urlCheckCache.set(cacheKey, result, CONFIG.CACHE_TTL); return result; } else { if (currentParts.length >= 2) { const currentMainDomain = currentParts.slice(-2).join('.'); const urlHost = urlStr.replace(/https?:\/\/([^\/]+).*/, '$1'); const urlParts = urlHost.split('.'); const urlMainDomain = urlParts.length >= 2 ? urlParts.slice(-2).join('.') : urlHost; const result = currentMainDomain !== urlMainDomain; urlCache.urlCheckCache.set(cacheKey, result, CONFIG.CACHE_TTL); return result; } else { const result = !urlStr.includes(currentHost); urlCache.urlCheckCache.set(cacheKey, result, CONFIG.CACHE_TTL); return result; } } } }, isSameOrigin(hostname) { return hostname === this.getCurrentHostname(); }, shouldInterceptByModule(element, moduleKey) { if (!currentConfig.modules[moduleKey]) return false; if (ProcessedElementsCache.isProcessed(element) || this.isParentProcessed(element)) return false; if (Whitelisting.isElementWhitelisted(element)) return false; return true; }, getBlockParentSubDomainsSetting() { return currentConfig.thirdPartySettings.blockParentSubDomains !== undefined ? currentConfig.thirdPartySettings.blockParentSubDomains : true; }, isUIElement(el) { return el?.classList && (el.classList.contains('mask') || el.classList.contains('panel') || el.id === 'ad-blocker-settings-container'); }, isPanelElement(el) { return el?.classList && el.classList.contains('panel'); }, isPanelClick(event) { const path = event.composedPath(); return path.some(el => this.isUIElement(el)); } }; const LogManager = { logs: [], maxLogs: CONFIG.LOG_MAX, loggedContentIdentifiers: new LRUCache(CONFIG.LOG_MAX, CONFIG.LOG_IDENTIFIER_TTL), add(moduleKey, element, reason) { if (!currentConfig.modules.removeInlineScripts && !currentConfig.modules.removeExternalScripts && !currentConfig.modules.interceptThirdParty && !currentConfig.modules.blockDynamicScripts && !currentConfig.modules.scriptBlacklistMode) { return; } if (!Utils.isElement(element) && element !== null && typeof reason !== 'object') return; if (Whitelisting.isElementWhitelisted(element) || Whitelisting.isReasonWhitelisted(reason)) return; let elementIdentifier = '[未知元素]'; let interceptedContent = '[无法获取内容]'; let contentIdentifier = null; let resourceDomain = ''; if (Utils.isElement(element)) { const tagName = element.tagName; const id = element.id ? `#${element.id}` : ''; const className = element.className ? `.${element.className.split(/\s+/).join('.')}` : ''; elementIdentifier = `${tagName}${id}${className}`; contentIdentifier = Utils.getContentIdentifier(element); if (tagName === 'SCRIPT') { if (element.src) { interceptedContent = `外联脚本: ${Utils.truncateString(element.src, 200)}`; resourceDomain = Utils.getResourceHostname(element.src) || ''; } else { interceptedContent = `内嵌脚本: ${Utils.getScriptContentPreview(element)}`; } } else if (tagName === 'IFRAME') { interceptedContent = Utils.getIframeSrcPreview(element); if (element.src) resourceDomain = Utils.getResourceHostname(element.src) || ''; } else if (tagName === 'IMG') { const src = element.src || element.dataset.src || element.getAttribute('data-src') || ''; interceptedContent = Utils.truncateString(src, 200); if (src) resourceDomain = Utils.getResourceHostname(src) || ''; } else if (tagName === 'A') { interceptedContent = Utils.truncateString(element.href || '', 200); if (element.href) resourceDomain = Utils.getResourceHostname(element.href) || ''; } else if (tagName === 'LINK') { interceptedContent = Utils.truncateString(element.href || '', 200); if (element.href) resourceDomain = Utils.getResourceHostname(element.href) || ''; } else if (tagName === 'STYLE') { interceptedContent = Utils.truncateString(element.textContent, 200); } else if (tagName === 'EMBED') { interceptedContent = Utils.truncateString(element.src || '', 200); if (element.src) resourceDomain = Utils.getResourceHostname(element.src) || ''; } else if (tagName === 'OBJECT') { interceptedContent = Utils.truncateString(element.data || '', 200); if (element.data) resourceDomain = Utils.getResourceHostname(element.data) || ''; } else { interceptedContent = Utils.truncateString(element.outerHTML, 200); } } else if (reason && typeof reason.detail === 'string') { interceptedContent = Utils.truncateString(reason.detail, 200); elementIdentifier = reason.type ? `[${reason.type}]` : '[未知类型]'; contentIdentifier = Utils.getContentIdentifier(null, reason); if (reason.detail.includes('://')) { try { const urlMatch = reason.detail.match(/https?:\/\/[^\s]+/); if (urlMatch) resourceDomain = Utils.getResourceHostname(urlMatch[0]) || ''; } catch (e) {} } } if (!contentIdentifier) { contentIdentifier = `${moduleKey}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`; } if (this.loggedContentIdentifiers.has(contentIdentifier)) return; const logId = this.logs.length + 1; const logEntry = { id: logId, moduleKey: moduleKey, module: MODULE_NAMES[moduleKey] || moduleKey, element: elementIdentifier, content: interceptedContent, domain: resourceDomain, timestamp: Date.now(), contentIdentifier: contentIdentifier }; this.logs.push(logEntry); this.loggedContentIdentifiers.set(contentIdentifier, true); if (this.logs.length > this.maxLogs) { const removed = this.logs.shift(); this.loggedContentIdentifiers.delete(removed.contentIdentifier); } }, clearLoggedIdentifiers() { this.loggedContentIdentifiers.clear(); } }; const Whitelisting = { isElementWhitelisted(element) { if (!element || !Utils.isElement(element)) return false; const contentIdentifier = Utils.getContentIdentifier(element); if (contentIdentifier && currentConfig.whitelist.has(contentIdentifier)) return true; if (currentConfig.modules.interceptThirdParty) { const hostname = Utils.getResourceHostname(element.src || element.href || element.action || element.data || ''); if (hostname) { const resourceUrl = element.src || element.href || element.action || element.data || ''; if (urlCache.isWhitelisted(resourceUrl, currentConfig.thirdPartyWhitelist)) return true; } } const keywordWhitelist = currentConfig.keywordWhitelist; if (keywordWhitelist.size > 0) { const scriptContent = element.textContent || ''; const src = element.src || element.href || element.action || element.data || ''; for (const keyword of keywordWhitelist) { if (keyword && (scriptContent.includes(keyword) || src.includes(keyword))) return true; } } return false; }, isReasonWhitelisted(reason) { if (!reason || typeof reason.detail !== 'string') return false; const contentIdentifier = Utils.getContentIdentifier(null, reason); if (contentIdentifier && currentConfig.whitelist.has(contentIdentifier)) return true; if (currentConfig.modules.interceptThirdParty) { const urlMatch = reason.detail.match(/https?:\/\/[^\s]+/); if (urlMatch) { const url = urlMatch[0]; if (urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist)) return true; } } const keywordWhitelist = currentConfig.keywordWhitelist; if (keywordWhitelist.size > 0) { for (const keyword of keywordWhitelist) { if (keyword && reason.detail.includes(keyword)) return true; } } return false; }, add(contentIdentifier) { if (!contentIdentifier || contentIdentifier.trim() === '') return; currentConfig.whitelist.add(contentIdentifier); StorageManager.saveConfig(); }, addKeyword(keyword) { if (!keyword || keyword.trim() === '') return; currentConfig.keywordWhitelist.add(keyword.trim()); StorageManager.saveConfig(); }, removeKeywordsMatchingDomain(domain) { let changed = false; const keywordsToRemove = []; for (const keyword of currentConfig.keywordWhitelist) { if (domain.includes(keyword)) keywordsToRemove.push(keyword); } keywordsToRemove.forEach(k => { currentConfig.keywordWhitelist.delete(k); changed = true; }); if (changed) StorageManager.saveConfig(); }, clearAllWhitelists() { currentConfig.whitelist.clear(); currentConfig.keywordWhitelist.clear(); currentConfig.thirdPartyWhitelist = []; StorageManager.saveConfig(); } }; const ProcessedElementsCache = { _processedElements: new WeakSet(), isProcessed(element) { if (!Utils.isElement(element)) return false; return this._processedElements.has(element) || element.dataset.adblockProcessed === 'true'; }, markAsProcessed(element) { if (!Utils.isElement(element)) return; this._processedElements.add(element); element.dataset.adblockProcessed = 'true'; }, clear() { this._processedElements = new WeakSet(); } }; const ResourceCanceller = { cancelResourceLoading(element) { if (!Utils.isElement(element) || ProcessedElementsCache.isProcessed(element)) return; const tagName = element.tagName; if (tagName === 'IMG' && element.src) { element.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; element.srcset = ''; element.removeAttribute('srcset'); if (element.load) element.load(); } else if (tagName === 'IFRAME' && element.src) { element.src = 'about:blank'; element.style.display = 'none'; element.remove(); } else if (tagName === 'SCRIPT' && element.src) { element.src = ''; element.remove(); } else if (tagName === 'LINK' && element.rel === 'stylesheet' && element.href) { element.href = ''; element.remove(); } else if (tagName === 'STYLE') { element.textContent = ''; element.remove(); } else if (tagName === 'EMBED' && element.src) { element.src = ''; element.remove(); } else if (tagName === 'OBJECT' && element.data) { element.data = ''; element.remove(); } if (element.parentNode) element.parentNode.removeChild(element); } }; const TAG_HANDLERS = { SCRIPT: { srcAttr: 'src', inlineContent: true, check: function(element, moduleKey, reason) { const contentIdentifier = Utils.getContentIdentifier(element); if (contentIdentifier && !currentConfig.whitelist.has(contentIdentifier)) { LogManager.add(moduleKey, element, reason); if (moduleKey === 'removeExternalScripts' || moduleKey === 'scriptBlacklistMode') { ResourceCanceller.cancelResourceLoading(element); } else if (moduleKey === 'removeInlineScripts' && !element.src) { element.remove(); } ProcessedElementsCache.markAsProcessed(element); return true; } return false; } }, IFRAME: { srcAttr: 'src', check: function(element, moduleKey) { if (moduleKey !== 'interceptThirdParty') return false; const url = element.src; if (url && Utils.isThirdParty(url, Utils.getBlockParentSubDomainsSetting()) && !urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist) && !Array.from(currentConfig.keywordWhitelist).some(k => url.includes(k))) { LogManager.add(moduleKey, element, { type: 'THIRD_PARTY', detail: `IFRAME: ${Utils.truncateString(url,200)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return true; } return false; } }, IMG: { srcAttr: 'src', dataSrcAttr: 'data-src', check: function(element, moduleKey) { if (moduleKey !== 'interceptThirdParty') return false; const url = element.src || element.getAttribute('data-src'); if (url && Utils.isThirdParty(url, Utils.getBlockParentSubDomainsSetting()) && !urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist) && !Array.from(currentConfig.keywordWhitelist).some(k => url.includes(k))) { LogManager.add(moduleKey, element, { type: 'THIRD_PARTY', detail: `IMG: ${Utils.truncateString(url,200)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return true; } return false; } }, LINK: { srcAttr: 'href', check: function(element, moduleKey) { if (moduleKey !== 'interceptThirdParty') return false; const url = element.href; if (url && element.rel === 'stylesheet' && Utils.isThirdParty(url, Utils.getBlockParentSubDomainsSetting()) && !urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist) && !Array.from(currentConfig.keywordWhitelist).some(k => url.includes(k))) { LogManager.add(moduleKey, element, { type: 'THIRD_PARTY', detail: `LINK: ${Utils.truncateString(url,200)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return true; } return false; } }, EMBED: { srcAttr: 'src', check: function(element, moduleKey) { if (moduleKey !== 'interceptThirdParty') return false; const url = element.src; if (url && Utils.isThirdParty(url, Utils.getBlockParentSubDomainsSetting()) && !urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist) && !Array.from(currentConfig.keywordWhitelist).some(k => url.includes(k))) { LogManager.add(moduleKey, element, { type: 'THIRD_PARTY', detail: `EMBED: ${Utils.truncateString(url,200)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return true; } return false; } }, OBJECT: { srcAttr: 'data', check: function(element, moduleKey) { if (moduleKey !== 'interceptThirdParty') return false; const url = element.data; if (url && Utils.isThirdParty(url, Utils.getBlockParentSubDomainsSetting()) && !urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist) && !Array.from(currentConfig.keywordWhitelist).some(k => url.includes(k))) { LogManager.add(moduleKey, element, { type: 'THIRD_PARTY', detail: `OBJECT: ${Utils.truncateString(url,200)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return true; } return false; } }, A: { srcAttr: 'href', check: function(element, moduleKey) { if (moduleKey !== 'interceptThirdParty') return false; const url = element.href; if (url && Utils.isThirdParty(url, Utils.getBlockParentSubDomainsSetting()) && !urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist) && !Array.from(currentConfig.keywordWhitelist).some(k => url.includes(k))) { LogManager.add(moduleKey, element, { type: 'THIRD_PARTY', detail: `A: ${Utils.truncateString(url,200)}` }); ProcessedElementsCache.markAsProcessed(element); return true; } return false; } } }; class BaseModule { constructor(moduleKey) { this.moduleKey = moduleKey; this.enabled = false; this.observer = null; } init() { if (currentConfig.modules[this.moduleKey]) this.enable(); else this.disable(); } enable() { if (this.enabled) return; this.enabled = true; this.onEnable(); } disable() { if (!this.enabled) return; this.enabled = false; this.onDisable(); } onEnable() { } onDisable() { if (this.observer) { this.observer.disconnect(); this.observer = null; } } checkElement(element) { if (!Utils.shouldInterceptByModule(element, this.moduleKey)) return false; return this._checkElement(element); } _checkElement(element) { throw new Error('_checkElement must be implemented by subclass'); } } class RemoveInlineScriptsModule extends BaseModule { constructor() { super('removeInlineScripts'); this.attributeObserver = null; } onEnable() { _document.querySelectorAll('script:not([src])').forEach(script => this.checkElement(script)); if (currentConfig.inlineScriptStrictMode) { _document.querySelectorAll('*').forEach(el => this.sanitizeInlineEventAttributes(el)); } this.observer = new _MutationObserver(mutations => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.nodeType === 1) { if (currentConfig.inlineScriptStrictMode) this.sanitizeInlineEventAttributes(node); if (node.tagName === 'SCRIPT' && !node.src) this.checkElement(node); } } } }); this.observer.observe(_document.documentElement, { childList: true, subtree: true }); if (currentConfig.inlineScriptStrictMode) { this.attributeObserver = new _MutationObserver(mutations => { for (const mutation of mutations) { if (mutation.type === 'attributes' && mutation.target.nodeType === 1) { this.sanitizeInlineEventAttributes(mutation.target); } } }); this.attributeObserver.observe(_document.documentElement, { attributes: true, subtree: true, attributeFilter: ['onclick', 'onload', 'onerror', 'onmouseover', 'onfocus', 'onblur', 'onsubmit', 'onchange', 'onkeydown', 'onkeyup', 'href', 'src', 'action', 'data', 'formaction'] }); } } onDisable() { super.onDisable(); if (this.attributeObserver) { this.attributeObserver.disconnect(); this.attributeObserver = null; } } _checkElement(element) { if (element.tagName === 'SCRIPT' && !element.src) { return TAG_HANDLERS.SCRIPT.check(element, this.moduleKey, { type: '内嵌脚本移除', detail: `内容: ${Utils.truncateString(element.textContent,300)}` }); } return false; } sanitizeInlineEventAttributes(element) { if (!Utils.isElement(element) || ProcessedElementsCache.isProcessed(element)) return false; let modified = false; const attrs = element.attributes; if (attrs) { for (let i = attrs.length - 1; i >= 0; i--) { const attr = attrs[i]; if (attr.name.toLowerCase().startsWith('on') && typeof attr.value === 'string' && attr.value.trim() !== '') { const reason = { type: '内联事件', detail: `属性: ${attr.name}="${attr.value}"` }; if (!Whitelisting.isReasonWhitelisted(reason)) { LogManager.add(this.moduleKey, element, reason); element.removeAttribute(attr.name); modified = true; } } } } const dangerousAttrs = ['href', 'src', 'action', 'data', 'formaction']; dangerousAttrs.forEach(attr => { const val = element.getAttribute(attr); if (val && typeof val === 'string' && val.trim().toLowerCase().startsWith('javascript:')) { const reason = { type: 'javascript URL', detail: `${attr}="${val}"` }; if (!Whitelisting.isReasonWhitelisted(reason)) { LogManager.add(this.moduleKey, element, reason); element.removeAttribute(attr); modified = true; } } }); if (modified) ProcessedElementsCache.markAsProcessed(element); return modified; } } class RemoveExternalScriptsModule extends BaseModule { constructor() { super('removeExternalScripts'); } onEnable() { _document.querySelectorAll('script[src]').forEach(script => this.checkElement(script)); this.observer = new _MutationObserver(mutations => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.nodeType === 1 && node.tagName === 'SCRIPT' && node.src) this.checkElement(node); } } }); this.observer.observe(_document.documentElement, { childList: true, subtree: true }); } _checkElement(element) { if (element.tagName === 'SCRIPT' && element.src) { return TAG_HANDLERS.SCRIPT.check(element, this.moduleKey, { type: '外联脚本移除', detail: `SRC: ${Utils.truncateString(element.src,200)}` }); } return false; } } class ScriptBlacklistModeModule extends BaseModule { constructor() { super('scriptBlacklistMode'); } onEnable() { _document.querySelectorAll('script').forEach(script => this.checkElement(script)); this.observer = new _MutationObserver(mutations => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.nodeType === 1 && node.tagName === 'SCRIPT') this.checkElement(node); } } }); this.observer.observe(_document.documentElement, { childList: true, subtree: true }); } _checkElement(element) { if (element.tagName !== 'SCRIPT') return false; const blacklist = currentConfig.scriptBlacklist; if (!blacklist || blacklist.size === 0) return false; const scriptContent = element.textContent; const scriptSrc = element.src; let matched = false; let matchedKeyword = ''; for (const keyword of blacklist) { if (!keyword) continue; if (scriptSrc && scriptSrc.includes(keyword)) { matched = true; matchedKeyword = keyword; break; } if (!scriptSrc && scriptContent && scriptContent.includes(keyword)) { matched = true; matchedKeyword = keyword; break; } } if (matched) { LogManager.add(this.moduleKey, element, { type: 'SCRIPT_BLACKLIST', detail: `命中关键词: ${matchedKeyword} - ${scriptSrc ? `SRC: ${Utils.truncateString(scriptSrc,200)}` : `内嵌: ${Utils.truncateString(scriptContent,200)}`}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return true; } return false; } } class ThirdPartyInterceptionModule extends BaseModule { constructor() { super('interceptThirdParty'); this.originalSetAttribute = null; this.originalFetch = null; this.originalXhrOpen = null; this.originalXhrSend = null; this.restoredFns = []; } onEnable() { if (_fetch && _fetch.name === 'Proxy') return; this.stopInterception(); this.setupProxyInterception(); this.setupNetworkInterception(); this.setupMutationFallback(); } onDisable() { this.stopInterception(); } stopInterception() { if (this.originalSetAttribute) { _Element.prototype.setAttribute = this.originalSetAttribute; this.originalSetAttribute = null; } if (this.originalFetch) { _globals.fetch = this.originalFetch; this.originalFetch = null; } if (this.originalXhrOpen) { _XMLHttpRequest.prototype.open = this.originalXhrOpen; _XMLHttpRequest.prototype.send = this.originalXhrSend; this.originalXhrOpen = null; this.originalXhrSend = null; } this.restoredFns.forEach(fn => { try { fn(); } catch(e) {} }); this.restoredFns = []; if (this.observer) { this.observer.disconnect(); this.observer = null; } } setupProxyInterception() { const self = this; const shouldBlock = (url, tagName) => { if (!url) return false; if (urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist)) return false; if (Array.from(currentConfig.keywordWhitelist).some(keyword => url.includes(keyword))) return false; return Utils.isThirdParty(url, Utils.getBlockParentSubDomainsSetting()); }; const logAndCancel = (element, attr, url, tagName) => { LogManager.add(this.moduleKey, element, { type: 'THIRD_PARTY', detail: `${tagName}: ${Utils.truncateString(url,200)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); }; this.originalSetAttribute = _Element.prototype.setAttribute; const setAttributeProxy = new _Proxy(_Element.prototype.setAttribute, { apply(target, thisArg, args) { const [name, value] = args; const tagName = thisArg.tagName; if (TAG_HANDLERS[tagName] && TAG_HANDLERS[tagName].srcAttr === name && shouldBlock(value, tagName)) { logAndCancel(thisArg, name, value, tagName); return; } return Reflect.apply(target, thisArg, args); } }); _Element.prototype.setAttribute = setAttributeProxy; this.restoredFns.push(() => { _Element.prototype.setAttribute = this.originalSetAttribute; }); for (const tagName in TAG_HANDLERS) { const proto = _globals[`HTML${tagName}Element`]?.prototype; if (!proto) continue; const srcAttr = TAG_HANDLERS[tagName].srcAttr; const desc = Object.getOwnPropertyDescriptor(proto, srcAttr); if (desc && desc.set) { const originalSetter = desc.set; const setterProxy = new _Proxy(originalSetter, { apply(target, thisArg, args) { const [value] = args; if (shouldBlock(value, tagName)) { logAndCancel(thisArg, srcAttr, value, tagName); return; } return Reflect.apply(target, thisArg, args); } }); Object.defineProperty(proto, srcAttr, { set: setterProxy, get: desc.get, configurable: true, enumerable: true }); this.restoredFns.push(() => { Object.defineProperty(proto, srcAttr, desc); }); } } } setupNetworkInterception() { const self = this; const shouldBlock = (url) => { if (!url) return false; if (urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist)) return false; if (Array.from(currentConfig.keywordWhitelist).some(keyword => url.includes(keyword))) return false; return Utils.isThirdParty(url, Utils.getBlockParentSubDomainsSetting()); }; this.originalFetch = _fetch; const fetchProxy = new _Proxy(_fetch, { apply(target, thisArg, args) { const input = args[0]; const url = typeof input === 'string' ? input : input?.url; if (url && shouldBlock(url)) { LogManager.add(self.moduleKey, null, { type: 'THIRD_PARTY', detail: `FETCH: ${Utils.truncateString(url,200)}` }); return Promise.reject(new Error('拦截第三方请求')); } return Reflect.apply(target, thisArg, args); } }); _globals.fetch = fetchProxy; this.restoredFns.push(() => { _globals.fetch = this.originalFetch; }); this.originalXhrOpen = _XMLHttpRequest.prototype.open; this.originalXhrSend = _XMLHttpRequest.prototype.send; const openProxy = new _Proxy(_XMLHttpRequest.prototype.open, { apply(target, thisArg, args) { const method = args[0]; const url = args[1]; if (url && shouldBlock(url)) { LogManager.add(self.moduleKey, null, { type: 'THIRD_PARTY', detail: `XHR: ${Utils.truncateString(url,200)}` }); try { thisArg.open(method, 'about:blank', ...args.slice(2)); thisArg.abort(); } catch (e) {} throw new Error('拦截第三方请求'); } return Reflect.apply(target, thisArg, args); } }); _XMLHttpRequest.prototype.open = openProxy; this.restoredFns.push(() => { _XMLHttpRequest.prototype.open = this.originalXhrOpen; _XMLHttpRequest.prototype.send = this.originalXhrSend; }); } setupMutationFallback() { const self = this; this.observer = new _MutationObserver((mutations) => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.nodeType !== 1) continue; const tagName = node.tagName; if (TAG_HANDLERS[tagName]) { const srcAttr = TAG_HANDLERS[tagName].srcAttr; const dataSrcAttr = TAG_HANDLERS[tagName].dataSrcAttr; const value = node[srcAttr] || node.getAttribute(srcAttr) || (dataSrcAttr && node.getAttribute(dataSrcAttr)); if (value) { if (Utils.isThirdParty(value, Utils.getBlockParentSubDomainsSetting()) && !urlCache.isWhitelisted(value, currentConfig.thirdPartyWhitelist) && !Array.from(currentConfig.keywordWhitelist).some(keyword => value.includes(keyword))) { LogManager.add(self.moduleKey, node, { type: 'THIRD_PARTY', detail: `${tagName}: ${Utils.truncateString(value,200)}` }); ResourceCanceller.cancelResourceLoading(node); ProcessedElementsCache.markAsProcessed(node); } } } } } }); this.observer.observe(_document.documentElement, { childList: true, subtree: true }); } _checkElement(element) { const tagName = element.tagName; if (!TAG_HANDLERS[tagName]) return false; const blockParentSubDomains = Utils.getBlockParentSubDomainsSetting(); let shouldBlock = false; const handler = TAG_HANDLERS[tagName]; const srcAttr = handler.srcAttr; const dataSrcAttr = handler.dataSrcAttr; const value = element[srcAttr] || element.getAttribute(srcAttr) || (dataSrcAttr && element.getAttribute(dataSrcAttr)); if (value && Utils.isThirdParty(value, blockParentSubDomains) && !urlCache.isWhitelisted(value, currentConfig.thirdPartyWhitelist) && !Array.from(currentConfig.keywordWhitelist).some(k => value.includes(k))) { shouldBlock = true; } if (shouldBlock) { LogManager.add(this.moduleKey, element, { type: 'THIRD_PARTY', detail: `${tagName}: ${Utils.truncateString(value,200)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return true; } return false; } } const DynamicScriptInterceptor = { _enabled: false, originalEval: null, originalFunction: null, originalSetTimeout: null, originalSetInterval: null, originalClearTimeout: null, originalClearInterval: null, originalRequestAnimationFrame: null, originalCancelAnimationFrame: null, timerMap: new _Map(), rafMap: new _Map(), timerIdCounter: 1, rafIdCounter: 1, init() { if (currentConfig.modules.blockDynamicScripts) this.enable(); }, enable() { if (this._enabled) return; this._enabled = true; this.originalEval = _globals.eval; this.originalFunction = _globals.Function; this.originalSetTimeout = _globals.setTimeout; this.originalSetInterval = _globals.setInterval; this.originalClearTimeout = _globals.clearTimeout; this.originalClearInterval = _globals.clearInterval; this.originalRequestAnimationFrame = _globals.requestAnimationFrame; this.originalCancelAnimationFrame = _globals.cancelAnimationFrame; const self = this; _globals.eval = function(code) { if (typeof code === 'string') { const contentIdentifier = Utils.getContentIdentifier(null, { type: 'EVAL', detail: `代码: ${Utils.truncateString(code,200)}` }); if (contentIdentifier && !currentConfig.whitelist.has(contentIdentifier)) { LogManager.add('blockDynamicScripts', null, { type: 'EVAL', detail: `动态执行: ${Utils.truncateString(code,200)}` }); return undefined; } } return self.originalEval.call(this, code); }; _globals.Function = function(...args) { const code = args.length > 0 ? args[args.length-1] : ''; if (typeof code === 'string') { const contentIdentifier = Utils.getContentIdentifier(null, { type: 'FUNCTION_CONSTRUCTOR', detail: `代码: ${Utils.truncateString(code,200)}` }); if (contentIdentifier && !currentConfig.whitelist.has(contentIdentifier)) { LogManager.add('blockDynamicScripts', null, { type: 'FUNCTION_CONSTRUCTOR', detail: `Function构造器: ${Utils.truncateString(code,200)}` }); return function() {}; } } return self.originalFunction.apply(this, args); }; _globals.setTimeout = function(callback, delay, ...args) { if (typeof callback === 'string') { const contentIdentifier = Utils.getContentIdentifier(null, { type: 'SETTIMEOUT', detail: `代码: ${Utils.truncateString(callback,200)}` }); if (contentIdentifier && !currentConfig.whitelist.has(contentIdentifier)) { LogManager.add('blockDynamicScripts', null, { type: 'SETTIMEOUT', detail: `setTimeout: ${Utils.truncateString(callback,200)}` }); const fakeId = -Math.abs(self.timerIdCounter++); self.timerMap.set(fakeId, { type: 'timeout', originalCallback: callback }); return fakeId; } } return self.originalSetTimeout.call(this, callback, delay, ...args); }; _globals.setInterval = function(callback, delay, ...args) { if (typeof callback === 'string') { const contentIdentifier = Utils.getContentIdentifier(null, { type: 'SETINTERVAL', detail: `代码: ${Utils.truncateString(callback,200)}` }); if (contentIdentifier && !currentConfig.whitelist.has(contentIdentifier)) { LogManager.add('blockDynamicScripts', null, { type: 'SETINTERVAL', detail: `setInterval: ${Utils.truncateString(callback,200)}` }); const fakeId = -Math.abs(self.timerIdCounter++); self.timerMap.set(fakeId, { type: 'interval', originalCallback: callback }); return fakeId; } } return self.originalSetInterval.call(this, callback, delay, ...args); }; _globals.clearTimeout = function(id) { if (typeof id === 'number' && id < 0) { self.timerMap.delete(id); return; } return self.originalClearTimeout.call(this, id); }; _globals.clearInterval = function(id) { if (typeof id === 'number' && id < 0) { self.timerMap.delete(id); return; } return self.originalClearInterval.call(this, id); }; _globals.requestAnimationFrame = function(callback) { if (typeof callback === 'string') { const contentIdentifier = Utils.getContentIdentifier(null, { type: 'REQUESTANIMATIONFRAME', detail: `代码: ${Utils.truncateString(callback,200)}` }); if (contentIdentifier && !currentConfig.whitelist.has(contentIdentifier)) { LogManager.add('blockDynamicScripts', null, { type: 'REQUESTANIMATIONFRAME', detail: `requestAnimationFrame: ${Utils.truncateString(callback,200)}` }); const fakeId = -Math.abs(self.rafIdCounter++); self.rafMap.set(fakeId, { originalCallback: callback }); return fakeId; } } return self.originalRequestAnimationFrame.call(this, callback); }; _globals.cancelAnimationFrame = function(id) { if (typeof id === 'number' && id < 0) { self.rafMap.delete(id); return; } return self.originalCancelAnimationFrame.call(this, id); }; }, disable() { if (!this._enabled) return; this._enabled = false; _globals.eval = this.originalEval; _globals.Function = this.originalFunction; _globals.setTimeout = this.originalSetTimeout; _globals.setInterval = this.originalSetInterval; _globals.clearTimeout = this.originalClearTimeout; _globals.clearInterval = this.originalClearInterval; _globals.requestAnimationFrame = this.originalRequestAnimationFrame; _globals.cancelAnimationFrame = this.originalCancelAnimationFrame; this.originalEval = this.originalFunction = this.originalSetTimeout = this.originalSetInterval = null; this.originalClearTimeout = this.originalClearInterval = this.originalRequestAnimationFrame = this.originalCancelAnimationFrame = null; this.timerMap.clear(); this.rafMap.clear(); }, check() { return false; } }; const CSPModule = { init() {}, applyCSP() { if (!currentConfig.modules.manageCSP) return; const existingMeta = _document.querySelector('meta[http-equiv="Content-Security-Policy"]'); if (existingMeta) existingMeta.remove(); const enabledRules = currentConfig.cspRules.filter(rule => rule.enabled); if (enabledRules.length === 0) return; const directives = {}; enabledRules.forEach(rule => { const [directive, ...values] = rule.rule.split(' '); if (!directives[directive]) directives[directive] = new _Set(); values.forEach(value => directives[directive].add(value)); }); let policyString = ''; for (const directive in directives) { if (directives.hasOwnProperty(directive)) { const values = Array.from(directives[directive]).join(' '); policyString += `${directive} ${values}; `; } } policyString = policyString.trim(); if (policyString) { const tryInsert = () => { if (_document.head) { const meta = _document.createElement('meta'); meta.httpEquiv = "Content-Security-Policy"; meta.content = policyString; _document.head.appendChild(meta); } else { const observer = new _MutationObserver(() => { if (_document.head) { observer.disconnect(); const meta = _document.createElement('meta'); meta.httpEquiv = "Content-Security-Policy"; meta.content = policyString; _document.head.appendChild(meta); } }); observer.observe(_document.documentElement, { childList: true, subtree: true }); } }; tryInsert(); } }, removeCSP() { const existingMeta = _document.querySelector('meta[http-equiv="Content-Security-Policy"]'); if (existingMeta) existingMeta.remove(); }, updateRule(ruleId, enabled) { const rule = currentConfig.cspRules.find(r => r.id === ruleId); if (rule) rule.enabled = enabled; } }; const UI_CSS = ` .mask { position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0); backdrop-filter:blur(0px); z-index:${CONFIG.Z_INDEX}; display:flex; align-items:center; justify-content:center; transition: all 0.3s ease; pointer-events: auto; animation: fade-in 0.3s forwards; } .panel { background:#fff; border-radius:20px; box-shadow:0 10px 30px rgba(0,0,0,0.15); padding:16px 12px; display:flex; flex-direction:column; gap:10px; width:94vw; max-width:500px; font-family:system-ui,-apple-system,sans-serif; box-sizing:border-box; position:relative; transform: scale(0.9); opacity: 0; animation: scale-in 0.3s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; max-height:85vh; overflow-y:auto; } .title { margin:0 0 6px 0; font-size:16px; font-weight:700; color:#1a1a1a; text-align:center; word-break:break-all; line-height:1.3; padding:0 8px; } .btn-group { display:flex; flex-wrap:wrap; gap:8px; margin-top:4px; } .btn-group button { flex:1 0 calc(50% - 8px); min-width:100px; } button { border:none; border-radius:10px; padding:10px 8px; cursor:pointer; font-size:13px; font-weight:600; transition:all 0.2s; background:#f0f2f5; color:#444; display:flex; align-items:center; justify-content:center; min-height:40px; } button:hover { background:#e4e6e9; transform: translateY(-1px); } button:active { transform:scale(0.95); } button.primary { background:#007AFF; color:#fff; } button.primary:hover { background:#0063cc; box-shadow: 0 4px 12px rgba(0,122,255,0.3); } button.danger { background:#ff4d4f; color:#fff; } button.danger:hover { background:#d9363e; box-shadow: 0 4px 12px rgba(255,77,79,0.3); } textarea { width:100%; height:140px; border:1px solid #ddd; border-radius:10px; padding:10px; font-family:monospace; font-size:12px; resize:none; box-sizing:border-box; outline:none; line-height:1.4; } textarea:focus { border-color:#007AFF; box-shadow:0 0 0 2px rgba(0,122,255,0.1); } select { width:100%; padding:8px; border-radius:10px; border:1px solid #ddd; outline:none; font-size:13px; } .footer { display:flex; flex-direction:column; gap:6px; margin-top:6px; } .module-switch { display:flex; align-items:center; justify-content:space-between; padding:8px 12px; background:#f8f9fa; border-radius:10px; border:1px solid #eee; } .switch-label { font-size:14px; font-weight:600; color:#333; } .switch { position:relative; width:40px; height:24px; flex-shrink:0; } .switch input { opacity:0; width:0; height:0; } .slider { position:absolute; cursor:pointer; top:0; left:0; right:0; bottom:0; background-color:#ccc; transition:.4s; border-radius:24px; } .slider:before { position:absolute; content:""; height:18px; width:18px; left:3px; bottom:3px; background-color:white; transition:.4s; border-radius:50%; } input:checked + .slider { background-color:#007AFF; } input:checked + .slider:before { transform:translateX(16px); } .sub-panel { max-height:45vh; overflow-y:auto; background:#f9f9f9; padding:12px; border-radius:10px; border:1px solid #eee; } .log-entry { margin-bottom:10px; padding:10px; background:#fff; border-radius:8px; border-left:4px solid #007AFF; font-size:12px; position:relative; min-height: 60px; } .log-module { color:#007AFF; font-weight:bold; margin-bottom:3px; font-size:13px; } .log-content { color:#666; word-break:break-word; font-size:11px; max-height:180px; overflow-y:auto; white-space:normal; line-height:1.4; padding-right: 45px; } .whitelist-btn { position:absolute; top:8px; right:8px; background:#34C759; color:#fff; border:none; border-radius:5px; padding:3px 8px; font-size:10px; cursor:pointer; z-index: 1; } .csp-rule { display:flex; align-items:center; justify-content:space-between; padding:10px; background:#fff; border-radius:8px; margin-bottom:6px; } .csp-name { font-size:12px; color:#333; max-width:70%; } .whitelist-item { display:flex; align-items:center; justify-content:space-between; flex-wrap:nowrap; width:100%; padding:8px; background:#fff; border-radius:6px; margin-bottom:5px; } .whitelist-text { font-size:11px; color:#333; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; flex:1 1 auto; min-width:0; } .whitelist-item button { flex-shrink:0; margin-left:8px; } .keyword-highlight { background-color: #fff9c4; } .panel::-webkit-scrollbar { width:6px; } .panel::-webkit-scrollbar-track { background:#f1f1f1; border-radius:4px; } .panel::-webkit-scrollbar-thumb { background:#c1c1c1; border-radius:4px; } .panel::-webkit-scrollbar-thumb:hover { background:#a8a8a8; } .log-entry.whitelisted { background-color: #e8f5e8; } .log-entry.keyword-whitelisted { background-color: #e0f0ff; } .log-entry.blacklisted { background-color: #ffe0e0; } @media (prefers-color-scheme: dark) { .panel { background:#1c1c1e; color:#fff; } .title { color:#fff; } button { background:#2c2c2e; color:#ccc; } button:hover { background:#3a3a3c; } textarea { background:#2c2c2e; border-color:#444; color:#eee; } select { background:#2c2c2e; border-color:#444; color:#eee; } .module-switch { background:#2c2c2e; border-color:#444; } .switch-label { color:#eee; } .sub-panel { background:#2c2c2e; border-color:#444; } .log-entry { background:#1c1c1e; } .csp-rule { background:#1c1c1e; } .whitelist-item { background:#1c1c1e; } .whitelist-text { color:#eee; } .keyword-highlight { background-color: #4a4a2c; } .panel::-webkit-scrollbar-track { background:#2c2c2e; } .panel::-webkit-scrollbar-thumb { background:#555; } .panel::-webkit-scrollbar-thumb:hover { background:#666; } .log-entry.whitelisted { background-color: #2a4a2a; } .log-entry.keyword-whitelisted { background-color: #2a3a5a; } .log-entry.blacklisted { background-color: #5a2a2a; } } @keyframes fade-in { to { background:rgba(0,0,0,0.3); backdrop-filter:blur(8px); } } @keyframes scale-in { to { transform: scale(1); opacity: 1; } }`; class PanelManager { constructor() { this.shadowRoot = null; this.settingsContainer = null; this.ensureShadow(); } ensureShadow() { if (this.shadowRoot) return; this.settingsContainer = _document.createElement('div'); this.settingsContainer.id = 'ad-blocker-settings-container'; this.settingsContainer.style.cssText = 'position:absolute;top:0;left:0;z-index:2147483647;pointer-events:none;'; this.settingsContainer.setAttribute('data-adblock-safe', 'true'); _document.documentElement.appendChild(this.settingsContainer); this.shadowRoot = this.settingsContainer.attachShadow({ mode: 'closed' }); const style = _document.createElement('style'); style.textContent = UI_CSS; this.shadowRoot.appendChild(style); ProcessedElementsCache.markAsProcessed(this.settingsContainer); } createPanel(options) { const { title, contentHtml, onClose, onBack, buttons = [], hideBackButton = false } = options; this.ensureShadow(); setupNavigationBlocking(); const mask = _document.createElement('div'); mask.className = 'mask'; mask.setAttribute('data-adblock-safe', 'true'); const buttonHtml = buttons.map(btn => { return ``; }).join(''); const backButtonHtml = hideBackButton ? '' : ``; mask.innerHTML = `
${escapeHtml(title)}
${contentHtml}
${buttonHtml} ${backButtonHtml}
`; mask.addEventListener('click', (e) => { const path = e.composedPath(); const isPanel = path.some(el => Utils.isPanelElement(el)); if (!isPanel && e.target === mask) { teardownNavigationBlocking(); mask.remove(); if (onClose) onClose(); return; } const button = e.target.closest('button'); if (!button) return; const action = button.dataset.action || button.dataset.id; const index = button.dataset.index; if (action === 'backBtn') { teardownNavigationBlocking(); mask.remove(); if (onBack) onBack(); else this.showSettings(); return; } const matchedButton = buttons.find(btn => btn.id === action); if (matchedButton && matchedButton.onclick) { matchedButton.onclick(e, mask); return; } this.handlePanelAction(action, index, button, mask, e); }); mask.addEventListener('change', (e) => { const target = e.target; if (target.matches('.module-toggle')) { const key = target.dataset.key; const checked = target.checked; if (key === 'removeInlineScripts' && checked) { if (currentConfig.inlineScriptStrictMode === undefined) { const userChoice = confirm('是否启用严格模式?严格模式下会额外拦截内联事件(如onclick)和javascript:URL。\n\n这些通常用于点击弹窗、悬浮广告、自动跳转等。'); currentConfig.inlineScriptStrictMode = userChoice; } } if (key === 'interceptThirdParty' && checked) { if (currentConfig.thirdPartySettings.blockParentSubDomains === undefined) { const hostname = Utils.getCurrentHostname(); const mainDomain = hostname.split('.').slice(-2).join('.'); const exampleText = `当前域名:${hostname}\n主域名:${mainDomain}\n子域名:sub.${mainDomain}\n兄弟域名:other.${mainDomain}`; const userChoice = confirm(`是否拦截所有第三方资源(包括主域名、子域名、兄弟域名)?\n\n${exampleText}\n\n点击“确定”拦截所有第三方资源;点击“取消”只拦截完全无关的第三方域名。`); currentConfig.thirdPartySettings.blockParentSubDomains = userChoice; } } if (key === 'scriptBlacklistMode' && checked) { alert('脚本黑名单模块已开启。请点击“脚本黑名单”按钮添加需要拦截的关键词。'); } currentConfig.modules[key] = checked; StorageManager.saveConfig(); if (strongBlockingEnabled) disableStrongBlocking(); panelOpenCount = 0; _location.reload(); } else if (target.matches('.csp-toggle')) { const id = parseInt(target.dataset.id); const enabled = target.checked; CSPModule.updateRule(id, enabled); currentConfig.modules.manageCSP = currentConfig.cspRules.some(rule => rule.enabled); StorageManager.saveConfig(); _location.reload(); } }); this.shadowRoot.appendChild(mask); mask.style.pointerEvents = 'auto'; mask.querySelector('.panel').style.pointerEvents = 'auto'; return mask; } handlePanelAction(action, index, button, mask, event) { switch (action) { case 'deleteDiaryItem': { const diaryWhitelist = Array.from(currentConfig.whitelist); const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < diaryWhitelist.length) { const item = diaryWhitelist[idx]; if (item) { currentConfig.whitelist.delete(item); StorageManager.saveConfig(); if (centralScheduler) centralScheduler.clearCache(); urlCache.clear(); LogManager.clearLoggedIdentifiers(); this.showDiaryWhitelistPanel(mask); } } break; } case 'deleteKeywordItem': { const keywords = Array.from(currentConfig.keywordWhitelist); const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < keywords.length) { const kw = keywords[idx]; if (kw) { currentConfig.keywordWhitelist.delete(kw); StorageManager.saveConfig(); if (centralScheduler) centralScheduler.clearCache(); urlCache.clear(); LogManager.clearLoggedIdentifiers(); this.showKeywordWhitelistPanel(mask); } } break; } case 'deleteBlacklistItem': { const blacklist = Array.from(currentConfig.scriptBlacklist); const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < blacklist.length) { const kw = blacklist[idx]; if (kw) { currentConfig.scriptBlacklist.delete(kw); StorageManager.saveConfig(); if (centralScheduler) centralScheduler.clearCache(); urlCache.clear(); LogManager.clearLoggedIdentifiers(); this.showScriptBlacklistPanel(mask); } } break; } case 'deleteThirdPartyItem': { const whitelist = currentConfig.thirdPartyWhitelist; const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < whitelist.length) { const item = whitelist[idx]; if (item) { whitelist.splice(idx, 1); StorageManager.saveConfig(); Whitelisting.removeKeywordsMatchingDomain(item); if (centralScheduler) centralScheduler.clearCache(); urlCache.clear(); LogManager.clearLoggedIdentifiers(); this.showThirdPartyPanel(mask); } } break; } case 'whitelistLog': { const logs = LogManager.logs; const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < logs.length) { const logEntry = logs[idx]; if (logEntry && logEntry.contentIdentifier) { if (logEntry.domain && currentConfig.modules.interceptThirdParty) { if (!currentConfig.thirdPartyWhitelist.includes(logEntry.domain)) { currentConfig.thirdPartyWhitelist.push(logEntry.domain); logEntry.content = logEntry.content + ' (域名已加白)'; } } else { currentConfig.whitelist.add(logEntry.contentIdentifier); logEntry.content = logEntry.content + ' (已加白)'; } StorageManager.saveConfig(); if (centralScheduler) centralScheduler.clearCache(); urlCache.clear(); LogManager.clearLoggedIdentifiers(); this.showLogsPanel(mask); } } break; } case 'addToBlacklist': { const encodedContent = button.dataset.content; if (encodedContent) { const content = decodeURIComponent(encodedContent); currentConfig.scriptBlacklist.add(content); StorageManager.saveConfig(); button.textContent = '已加黑'; button.style.background = '#999'; button.disabled = true; } break; } case 'addKeywordWhitelist': { const input = mask.querySelector('#keywordWhitelistInput'); const keyword = input.value.trim(); if (keyword) { Whitelisting.addKeyword(keyword); const logs = LogManager.logs; this.showLogsPanel(mask); } break; } case 'addWhitelist': { const input = mask.querySelector('#newWhitelist'); let value = input.value.trim(); if (value) { value = value.replace(/^https?:\/\//, ''); try { const urlObj = new URL('http://' + value); value = urlObj.hostname + (urlObj.pathname !== '/' ? urlObj.pathname : ''); } catch (e) {} const whitelist = currentConfig.thirdPartyWhitelist; if (!whitelist.includes(value)) { whitelist.push(value); StorageManager.saveConfig(); } input.value = ''; if (centralScheduler) centralScheduler.clearCache(); urlCache.clear(); LogManager.clearLoggedIdentifiers(); this.showThirdPartyPanel(mask); } break; } case 'addBlacklist': { const input = mask.querySelector('#newBlacklistKeyword'); const kw = input.value.trim(); if (kw) { currentConfig.scriptBlacklist.add(kw); StorageManager.saveConfig(); input.value = ''; if (centralScheduler) centralScheduler.clearCache(); urlCache.clear(); LogManager.clearLoggedIdentifiers(); this.showScriptBlacklistPanel(mask); } break; } case 'clearAllDiary': { currentConfig.whitelist.clear(); StorageManager.saveConfig(); this.showDiaryWhitelistPanel(mask); break; } case 'clearAllKeyword': { currentConfig.keywordWhitelist.clear(); StorageManager.saveConfig(); this.showKeywordWhitelistPanel(mask); break; } case 'clearAllBlacklist': { currentConfig.scriptBlacklist.clear(); StorageManager.saveConfig(); this.showScriptBlacklistPanel(mask); break; } case 'clearAllThirdParty': { currentConfig.thirdPartyWhitelist = []; StorageManager.saveConfig(); this.showThirdPartyPanel(mask); break; } case 'showScriptList': { this.showScriptListPanel(mask); break; } case 'closeBtn': { mask.remove(); teardownNavigationBlocking(); break; } case 'enableCSP': case 'disableCSP': case 'allOn': case 'allOff': break; default: break; } } showSettings() { const oldMask = this.shadowRoot.querySelector('.mask'); if (oldMask) oldMask.remove(); const moduleSwitches = Object.keys(MODULE_NAMES).map(key => `
${escapeHtml(MODULE_NAMES[key])}
`).join(''); this.createPanel({ title: '🛡️广告拦截设置', contentHtml: `
功能模块:
${moduleSwitches} `, buttons: [ { id: 'viewLogs', text: `拦截日志 (${LogManager.logs.length})`, onclick: (e, mask) => { this.showLogsPanel(mask); } }, { id: 'manageCSP', text: 'CSP策略管理', onclick: (e, mask) => { this.showCSPPanel(mask); } }, { id: 'manageDiaryWhitelist', text: '日记白名单', onclick: (e, mask) => { this.showDiaryWhitelistPanel(mask); } }, { id: 'manageThirdParty', text: '第三方白名单', onclick: (e, mask) => { this.showThirdPartyPanel(mask); } }, { id: 'manageKeywordWhitelist', text: '关键词白名单', onclick: (e, mask) => { this.showKeywordWhitelistPanel(mask); } }, { id: 'manageScriptBlacklist', text: '脚本黑名单', onclick: (e, mask) => { this.showScriptBlacklistPanel(mask); } }, { id: 'closePanel', text: '返回网页', onclick: (e, mask) => { mask.remove(); teardownNavigationBlocking(); } } ], hideBackButton: true }); } showDiaryWhitelistPanel(parentMask) { parentMask?.remove(); const diaryWhitelist = Array.from(currentConfig.whitelist); const itemsHtml = diaryWhitelist.length > 0 ? diaryWhitelist.map((item, index) => `
${escapeHtml(item)}
`).join('') : '
日记白名单为空
'; this.createPanel({ title: `日记白名单 (${diaryWhitelist.length}项)`, contentHtml: `
查看和管理拦截日记中添加的白名单条目
${itemsHtml}
`, buttons: [], onBack: () => this.showSettings() }); } showKeywordWhitelistPanel(parentMask) { parentMask?.remove(); const keywords = Array.from(currentConfig.keywordWhitelist); const itemsHtml = keywords.length > 0 ? keywords.map((kw, index) => `
${escapeHtml(kw)}
`).join('') : '
关键词白名单为空
'; this.createPanel({ title: `关键词白名单 (${keywords.length}项)`, contentHtml: `
查看和管理通过关键词添加的白名单条目
${itemsHtml}
`, buttons: [], onBack: () => this.showSettings() }); } showScriptListPanel(parentMask) { parentMask?.remove(); const scripts = Array.from(_document.scripts); const scriptItems = scripts.map((script, index) => { const isExternal = !!script.src; let content = isExternal ? `外联脚本: ${script.src}` : `内嵌脚本: ${script.textContent}`; return { index: index+1, isExternal, content, script }; }); const blacklistSet = currentConfig.scriptBlacklist; const listHtml = scriptItems.length > 0 ? scriptItems.map(item => { const isBlacklisted = blacklistSet.has(item.isExternal ? item.script.src : item.script.textContent); const logEntryClass = 'log-entry' + (isBlacklisted ? ' blacklisted' : ''); return `
脚本 #${item.index} - ${item.isExternal ? '外联' : '内嵌'}
${escapeHtml(item.content)}
`; }).join('') : '
未找到任何脚本
'; this.createPanel({ title: `当前网页脚本列表 (共${scriptItems.length}个)`, contentHtml: `
点击「加黑」将整个脚本内容添加到脚本黑名单
${listHtml}
`, buttons: [], onBack: () => this.showScriptBlacklistPanel() }); } showScriptBlacklistPanel(parentMask) { parentMask?.remove(); const blacklist = Array.from(currentConfig.scriptBlacklist); const itemsHtml = blacklist.length > 0 ? blacklist.map((kw, index) => `
${escapeHtml(kw)}
`).join('') : '
脚本黑名单为空
'; this.createPanel({ title: `脚本黑名单 (${blacklist.length}项)`, contentHtml: `
脚本黑名单模式将拦截内嵌/外联脚本中匹配这些关键词的资源
${itemsHtml}
`, buttons: [], onBack: () => this.showSettings() }); _setTimeout(() => { const mask = this.shadowRoot.querySelector('.mask:last-child'); if (!mask) return; const input = mask.querySelector('#newBlacklistKeyword'); if (input) { input.addEventListener('keypress', (e) => { if (e.key === 'Enter') { const addBtn = mask.querySelector('[data-id="addBlacklist"]'); if (addBtn) addBtn.click(); } }); } }, 0); } showLogsPanel(parentMask) { parentMask?.remove(); const logs = LogManager.logs; const keywordWhitelist = Array.from(currentConfig.keywordWhitelist); const whitelistSet = currentConfig.whitelist; const logsHtml = logs.length > 0 ? logs.map((log, index) => { const isWhitelisted = whitelistSet.has(log.contentIdentifier); const isKeywordWhitelisted = !isWhitelisted && keywordWhitelist.some(kw => (log.content && log.content.includes(kw)) || (log.domain && log.domain.includes(kw)) ); const logEntryClass = 'log-entry' + (isWhitelisted ? ' whitelisted' : '') + (isKeywordWhitelisted ? ' keyword-whitelisted' : ''); return `
${escapeHtml(log.module)} - ${escapeHtml(log.element)}
${escapeHtml(log.content)}
${log.domain ? `
域名: ${escapeHtml(log.domain)}
` : ''}
`; }).join('') : '
暂无拦截记录
'; this.createPanel({ title: `拦截日志 (${logs.length}条)`, contentHtml: `
关键词加白(添加包含关键词的脚本到白名单):
${logsHtml}
`, buttons: [], onBack: () => this.showSettings() }); _setTimeout(() => { const mask = this.shadowRoot.querySelector('.mask:last-child'); if (!mask) return; const input = mask.querySelector('#keywordWhitelistInput'); if (input) { input.addEventListener('keypress', (e) => { if (e.key === 'Enter') { const addBtn = mask.querySelector('[data-id="addKeywordWhitelist"]'); if (addBtn) addBtn.click(); } }); } }, 0); } showCSPPanel(parentMask) { parentMask?.remove(); const rulesHtml = currentConfig.cspRules.map(rule => `
${escapeHtml(rule.name)}
`).join(''); this.createPanel({ title: 'CSP策略管理', contentHtml: `
当前状态: ${currentConfig.modules.manageCSP ? '✅已启用' : '❌已禁用'}
${rulesHtml}
`, buttons: [], onBack: () => this.showSettings() }); } showThirdPartyPanel(parentMask) { parentMask?.remove(); const whitelist = currentConfig.thirdPartyWhitelist; const itemsHtml = whitelist.length > 0 ? whitelist.map((item, index) => `
${escapeHtml(item)}
`).join('') : '
白名单为空
'; this.createPanel({ title: `第三方白名单 (${whitelist.length}项)`, contentHtml: `
已拦截的第三方域名可以添加到白名单中
${itemsHtml}
`, buttons: [], onBack: () => this.showSettings() }); _setTimeout(() => { const mask = this.shadowRoot.querySelector('.mask:last-child'); if (!mask) return; const input = mask.querySelector('#newWhitelist'); if (input) { input.addEventListener('keypress', (e) => { if (e.key === 'Enter') { const addBtn = mask.querySelector('[data-id="addWhitelist"]'); if (addBtn) addBtn.click(); } }); } }, 0); } } class CentralScheduler { constructor(modules) { this.modules = modules; this.elementCheckCache = new WeakSet(); this.urlCheckCache = new LRUCache(500, CONFIG.CACHE_TTL); } shouldProcessElement(element) { if (!Utils.isElement(element)) return false; if (this.elementCheckCache.has(element)) return false; if (ProcessedElementsCache.isProcessed(element)) return false; if (Utils.isParentProcessed(element)) return false; if (element.getAttribute('data-adblock-safe') === 'true') return false; return true; } processElement(element) { if (!this.shouldProcessElement(element)) return false; this.elementCheckCache.add(element); for (const module of this.modules) { if (module.enabled && module.checkElement(element)) { ProcessedElementsCache.markAsProcessed(element); return true; } } return false; } processUrl(url, type) { if (!url) return false; const cacheKey = `url_${url}_${type}`; if (this.urlCheckCache.has(cacheKey)) return this.urlCheckCache.get(cacheKey); let result = false; if (currentConfig.modules.interceptThirdParty) { const blockParentSubDomains = Utils.getBlockParentSubDomainsSetting(); if (Utils.isThirdParty(url, blockParentSubDomains) && !urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist)) { if (!Array.from(currentConfig.keywordWhitelist).some(keyword => url.includes(keyword))) { result = true; } } } this.urlCheckCache.set(cacheKey, result, CONFIG.CACHE_TTL); return result; } clearCache() { this.elementCheckCache = new WeakSet(); this.urlCheckCache.clear(); urlCache.clear(); } } const UIController = { initialized: false, mutationObserver: null, batchProcessingQueue: [], batchSize: CONFIG.BATCH_SIZE, isProcessingBatch: false, lastProcessTime: 0, panelManager: null, modules: [], init() { if (this.initialized) return; this.initialized = true; this.applyInitialModuleStates(); this.registerMenuCommands(); this.panelManager = new PanelManager(); this.createModules(); this.applyModuleSettings(); this.setupObservers(); this.setupResourceScan(); }, applyInitialModuleStates() { Object.keys(DEFAULT_MODULE_STATE).forEach(key => { if (currentConfig.modules[key] === undefined) currentConfig.modules[key] = DEFAULT_MODULE_STATE[key]; }); }, registerMenuCommands() { GM_registerMenuCommand('⚙️ 广告拦截设置面板', () => this.panelManager.showSettings()); GM_registerMenuCommand('🗑️ 清空所有白名单', () => { if (confirm('确定清空当前域名的所有白名单(包括第三方白名单、关键词白名单等)吗?')) { Whitelisting.clearAllWhitelists(); if (centralScheduler) centralScheduler.clearCache(); urlCache.clear(); LogManager.clearLoggedIdentifiers(); GM_notification({ text: '所有白名单已清空', title: '广告拦截器' }); _location.reload(); } }); GM_registerMenuCommand('🔄 重置所有设置', () => { if (confirm('确定重置所有设置吗?这将清空所有白名单并关闭所有模块,恢复到初始状态。')) { StorageManager.resetAllSettings(); if (centralScheduler) centralScheduler.clearCache(); urlCache.clear(); LogManager.clearLoggedIdentifiers(); GM_notification({ text: '所有设置已重置', title: '广告拦截器' }); _location.reload(); } }); }, createModules() { this.modules = [ new RemoveInlineScriptsModule(), new RemoveExternalScriptsModule(), new ScriptBlacklistModeModule(), new ThirdPartyInterceptionModule() ]; }, applyModuleSettings() { this.modules.forEach(module => module.init()); DynamicScriptInterceptor.init(); CSPModule.init(); centralScheduler = new CentralScheduler(this.modules); }, setupObservers() { const relevantModulesEnabled = this.modules.some(m => m.enabled) || currentConfig.modules.blockDynamicScripts; if (!relevantModulesEnabled) return; this.mutationObserver = new _MutationObserver(Utils.throttle((mutations) => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.nodeType === 1 && !ProcessedElementsCache.isProcessed(node) && !Utils.isParentProcessed(node)) { this.addToBatchProcessingQueue(node); } } } }, CONFIG.THROTTLE_LIMIT)); this.mutationObserver.observe(_document.documentElement, { childList: true, subtree: true }); this.processExistingElementsBatch(); }, setupResourceScan() { if (currentConfig.modules.interceptThirdParty) { _document.addEventListener('DOMContentLoaded', () => { _setTimeout(() => this.scanExistingResources(), 1000); }); } }, scanExistingResources() { const blockParentSubDomains = Utils.getBlockParentSubDomainsSetting(); const selectors = ['script[src]', 'iframe[src]', 'img[src]', 'img[data-src]', 'embed[src]', 'object[data]', 'link[href]']; selectors.forEach(selector => { try { const elements = _document.querySelectorAll(selector); elements.forEach(element => { if (ProcessedElementsCache.isProcessed(element) || Utils.isParentProcessed(element)) return; const tagName = element.tagName; let url = ''; if (tagName === 'SCRIPT') url = element.src; else if (tagName === 'IFRAME') url = element.src; else if (tagName === 'IMG') url = element.src || element.getAttribute('data-src'); else if (tagName === 'EMBED') url = element.src; else if (tagName === 'OBJECT') url = element.data; else if (tagName === 'LINK') url = element.href; if (url && Utils.isThirdParty(url, blockParentSubDomains) && !urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist)) { const contentIdentifier = Utils.getContentIdentifier(element); if (contentIdentifier && !currentConfig.whitelist.has(contentIdentifier)) { LogManager.add('interceptThirdParty', element, { type: 'THIRD_PARTY_SCAN', detail: `扫描发现: ${tagName}: ${Utils.truncateString(url,200)}` }); } } }); } catch (e) {} }); }, addToBatchProcessingQueue(element) { if (element.getAttribute && element.getAttribute('data-adblock-safe') === 'true') { ProcessedElementsCache.markAsProcessed(element); return; } this.batchProcessingQueue.push(element); if (!this.isProcessingBatch) this.processBatch(); }, processBatch() { if (!centralScheduler) return; this.isProcessingBatch = true; const processChunk = () => { const now = Date.now(); if (now - this.lastProcessTime < 16) { _requestAnimationFrame(processChunk); return; } const chunk = this.batchProcessingQueue.splice(0, this.batchSize); this.lastProcessTime = now; chunk.forEach(node => centralScheduler.processElement(node)); if (this.batchProcessingQueue.length > 0) _requestAnimationFrame(processChunk); else this.isProcessingBatch = false; }; _requestAnimationFrame(processChunk); }, processExistingElementsBatch() { const selector = 'script, iframe, img, a[href], style, link[rel="preload"], link[rel="prefetch"], embed, object, link[href]'; const elementsToProcess = Array.from(_document.querySelectorAll(selector)); const processInChunks = () => { const chunk = elementsToProcess.splice(0, this.batchSize * 2); chunk.forEach(element => { if (!ProcessedElementsCache.isProcessed(element) && !Utils.isParentProcessed(element)) { this.addToBatchProcessingQueue(element); } }); if (elementsToProcess.length > 0) _setTimeout(processInChunks, 0); }; processInChunks(); } }; StorageManager.loadConfig(); if (currentConfig.modules.blockDynamicScripts) DynamicScriptInterceptor.init(); let centralScheduler = null; function safeInit() { if (_document.documentElement) { UIController.init(); if (currentConfig.modules.manageCSP) CSPModule.applyCSP(); return true; } return false; } if (!safeInit()) { const mo = new _MutationObserver(() => { if (safeInit()) mo.disconnect(); }); mo.observe(_document, { childList: true }); _document.addEventListener('DOMContentLoaded', () => { if (!safeInit()) _setTimeout(safeInit, 100); }, { once: true }); _setTimeout(() => { if (!safeInit()) UIController.init(); }, 5000); } })();