// ==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 = `