// ==UserScript== // @name 网页广告拦截器 // @namespace http://tampermonkey.net/ // @version 5.4.1 // @author DeepSeek&Gemini // @description 一个手机端浏览器能用的强大的广告拦截器 // @match *://*/* // @license MIT // @grant unsafeWindow // @grant GM_setValue // @grant GM_getValue // @grant GM_deleteValue // @grant GM_registerMenuCommand // @grant GM_notification // @grant GM_listValues // @run-at document-start // ==/UserScript== (function () { 'use strict'; const DEFAULT_MODULE_STATE = { removeInlineScripts: false, removeExternalScripts: false, interceptThirdParty: false, blockDynamicScripts: false, manageCSP: false, scriptBlacklistMode: true }; const DEFAULT_CSP_RULES_TEMPLATE = [ { id: 1, name: '只允许同源外部脚本', rule: "script-src 'self'", enabled: false }, { id: 2, name: '只允许同源外部样式', rule: "style-src 'self'", enabled: false }, { id: 3, name: '只允许同源图片', rule: "img-src 'self'", 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 } ]; const BUILTIN_BLACKLIST_KEYWORDS = [ 'hm.baidu.com', 'tongji()', 'push.js', '{return void 0!==b[a]?b[a]:a}).join("")}', '${scripts[randomIndex]}', '${scripts[Math.random()', '"https://"+Date.parse(new Date())+', '"https://"+(new Date().getDate())+', 'https://{randomstr}.', 'new Function(t)()', 'new Function(b)()', 'new Function(c)()', 'new Function(t);', 'new Function(b);', 'new Function(c);', 'new Function(\'d\',e)', 'new Function(document[', 'new Function(function(p,a,c,k,e,d)', 'function a(a){', 'function b(b){', 'function c(c){', 'function updateCarousel()', 'Math.floor(2147483648 * Math.random());', 'Math.floor(Math.random()*url.length)', 'Math.floor(Math.random() * urls.length)', 'new Date()[\'getTime\']()', 'newDate=new window', 'Math.floor(((new Date()).getTime()', '&&navigator[', '=navigator;', 'navigator.platform){setTimeout(function', 'disableDebugger', 'blockDeveloperTools', '["Date"]())[\'getTime\']()', '\');', '<\\/\'+\'s\'+\'c\'+\'ri\'+\'pt\'+\'>\');', '(\'#htmlContenthtml\').html', 'D.createElement(\'span\');', 'window.$m(', '{win:false,mac:false,xll:false}', 'function|getDate', 'parseInt(Math[\'random\']' ]; 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: false, thirdPartyStrictMode: false, thirdPartyStrictMethod: false, spoofUAEnabled: false, residualCleanupEnabled: false, cssUniversalHideEnabled: false, iframeUIFix: false, redirectBlockerEnabled: false, builtinBlacklistEnabled: true, removedBuiltinKeywords: new Set() }; const ConfigUpdater = { _saveTimer: null, _debounceDelay: 150, set(key, value) { const keys = key.split('.'); let obj = currentConfig; for (let i = 0; i < keys.length - 1; i++) { obj = obj[keys[i]]; } obj[keys[keys.length - 1]] = value; this.scheduleSave(); }, scheduleSave() { if (this._saveTimer) clearTimeout(this._saveTimer); this._saveTimer = setTimeout(() => { StorageManager.saveConfig(); this._saveTimer = null; }, this._debounceDelay); }, saveNow() { if (this._saveTimer) { clearTimeout(this._saveTimer); this._saveTimer = null; } StorageManager.saveConfig(); } }; 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 (Array.isArray(data.removedBuiltinKeywords)) currentConfig.removedBuiltinKeywords = new Set(data.removedBuiltinKeywords); if (data.inlineScriptStrictMode !== undefined) currentConfig.inlineScriptStrictMode = data.inlineScriptStrictMode; if (data.thirdPartyStrictMode !== undefined) currentConfig.thirdPartyStrictMode = data.thirdPartyStrictMode; if (data.thirdPartyStrictMethod !== undefined) currentConfig.thirdPartyStrictMethod = data.thirdPartyStrictMethod; if (data.spoofUAEnabled !== undefined) currentConfig.spoofUAEnabled = data.spoofUAEnabled; if (data.residualCleanupEnabled !== undefined) currentConfig.residualCleanupEnabled = data.residualCleanupEnabled; if (data.cssUniversalHideEnabled !== undefined) currentConfig.cssUniversalHideEnabled = data.cssUniversalHideEnabled; if (data.iframeUIFix !== undefined) currentConfig.iframeUIFix = data.iframeUIFix; if (data.redirectBlockerEnabled !== undefined) currentConfig.redirectBlockerEnabled = data.redirectBlockerEnabled; if (data.builtinBlacklistEnabled !== undefined) currentConfig.builtinBlacklistEnabled = data.builtinBlacklistEnabled; } } catch (e) { /* ignore parse errors */ } if (!currentConfig.thirdPartySettings) currentConfig.thirdPartySettings = {}; if (!currentConfig.thirdPartyWhitelist) currentConfig.thirdPartyWhitelist = []; if (currentConfig.thirdPartySettings.blockParentSubDomains === undefined) currentConfig.thirdPartySettings.blockParentSubDomains = true; if (currentConfig.inlineScriptStrictMode === undefined) currentConfig.inlineScriptStrictMode = false; if (currentConfig.thirdPartyStrictMode === undefined) currentConfig.thirdPartyStrictMode = false; if (currentConfig.thirdPartyStrictMethod === undefined) currentConfig.thirdPartyStrictMethod = false; if (currentConfig.residualCleanupEnabled === undefined) currentConfig.residualCleanupEnabled = false; if (currentConfig.cssUniversalHideEnabled === undefined) currentConfig.cssUniversalHideEnabled = false; if (currentConfig.iframeUIFix === undefined) currentConfig.iframeUIFix = false; if (currentConfig.redirectBlockerEnabled === undefined) currentConfig.redirectBlockerEnabled = false; if (currentConfig.builtinBlacklistEnabled === undefined) currentConfig.builtinBlacklistEnabled = true; const legacySpoof = GM_getValue('spoofUAEnabled', null); if (legacySpoof !== null) { currentConfig.spoofUAEnabled = legacySpoof; GM_deleteValue('spoofUAEnabled'); this.saveConfig(); } }, 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, removedBuiltinKeywords: Array.from(currentConfig.removedBuiltinKeywords), inlineScriptStrictMode: currentConfig.inlineScriptStrictMode, thirdPartyStrictMode: currentConfig.thirdPartyStrictMode, thirdPartyStrictMethod: currentConfig.thirdPartyStrictMethod, spoofUAEnabled: currentConfig.spoofUAEnabled, residualCleanupEnabled: currentConfig.residualCleanupEnabled, cssUniversalHideEnabled: currentConfig.cssUniversalHideEnabled, iframeUIFix: currentConfig.iframeUIFix, redirectBlockerEnabled: currentConfig.redirectBlockerEnabled, builtinBlacklistEnabled: currentConfig.builtinBlacklistEnabled }; 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 = false; currentConfig.thirdPartyStrictMode = false; currentConfig.thirdPartyStrictMethod = false; currentConfig.spoofUAEnabled = false; currentConfig.residualCleanupEnabled = false; currentConfig.cssUniversalHideEnabled = false; currentConfig.iframeUIFix = false; currentConfig.redirectBlockerEnabled = false; currentConfig.builtinBlacklistEnabled = true; currentConfig.removedBuiltinKeywords.clear(); this.saveConfig(); } }; StorageManager.loadConfig(); const CONFIG = { Z_INDEX: 2147483640, CACHE_TTL: 300000, BATCH_SIZE: 20, LOG_MAX: 50, LOG_IDENTIFIER_TTL: 300000, STRONG_BLOCK_TIMEOUT: 600000, DEBOUNCE_WAIT: 100, THROTTLE_LIMIT: 100, RESIDUAL_MIN_WIDTH: 30, RESIDUAL_MIN_HEIGHT: 30, RESIDUAL_AD_SELECTORS: 'div, span, embed', 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 _Node = _globals.Node; 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; const _IntersectionObserver = _globals.IntersectionObserver; const _AbortController = _globals.AbortController; const _requestIdleCallback = _globals.requestIdleCallback || function (cb) { return _setTimeout(() => cb({ timeRemaining: () => 50, didTimeout: false }), 1); }; const _cancelIdleCallback = _globals.cancelIdleCallback || _clearTimeout; function escapeHtml(unsafe) { if (unsafe == null) return ''; return String(unsafe) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, ''') .replace(/`/g, '`') .replace(/\//g, '\\/'); } function generateContentHash(str, maxLength = 500) { if (typeof str !== 'string') return ''; const content = str.slice(0, maxLength); let hash = 0; for (let i = 0; i < content.length; i++) { const char = content.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; } return 'hash_' + Math.abs(hash).toString(36); } 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; } } const PUBLIC_SUFFIX_LIST = new Set([ 'co.uk', 'org.uk', 'me.uk', 'ltd.uk', 'plc.uk', 'net.uk', 'sch.uk', 'ac.uk', 'gov.uk', 'com.cn', 'net.cn', 'org.cn', 'gov.cn', 'edu.cn', 'co.jp', 'ne.jp', 'or.jp', 'go.jp', 'ac.jp', 'ad.jp', 'com.au', 'net.au', 'org.au', 'edu.au', 'gov.au', 'asn.au', 'id.au', 'co.nz', 'org.nz', 'net.nz', 'edu.nz', 'govt.nz', 'com.br', 'net.br', 'org.br', 'gov.br', 'edu.br', 'co.in', 'net.in', 'org.in', 'gov.in', 'ac.in', 'res.in', 'co.kr', 'ne.kr', 'or.kr', 'go.kr', 'ac.kr', 'com.tw', 'net.tw', 'org.tw', 'gov.tw', 'edu.tw', 'idv.tw' ]); 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; this.hostnameCache.set(cacheKey, hostname, CONFIG.CACHE_TTL); return hostname; } catch (e) { this.hostnameCache.set(cacheKey, null, 30000); return null; } } isIPv4(hostname) { return /^(\d{1,3}\.){3}\d{1,3}$/.test(hostname); } getDomain(hostname) { if (!hostname) return null; const cacheKey = `domain_${hostname}`; if (this.domainCache.has(cacheKey)) return this.domainCache.get(cacheKey); if (this.isIPv4(hostname)) { this.domainCache.set(cacheKey, hostname, CONFIG.CACHE_TTL); return hostname; } const parts = hostname.split('.'); let domain = hostname; for (let i = 1; i <= parts.length; i++) { const candidate = parts.slice(-i).join('.'); if (PUBLIC_SUFFIX_LIST.has(candidate)) { if (i + 1 <= parts.length) { domain = parts.slice(-(i + 1)).join('.'); } else { domain = candidate; } break; } } if (domain === hostname && parts.length > 2) { domain = 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 currentDomain = this.getDomain(currentHost); const resourceDomain = this.getDomain(resourceHostname); isThirdParty = currentDomain !== resourceDomain; } 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) { if (!pattern) continue; try { if (pattern.includes('://')) { if (url.includes(pattern)) { isWhitelisted = true; break; } } else { const urlHost = new URL(url, _location.href).hostname; let patternHost = pattern.startsWith('*.') ? pattern.substring(2) : pattern; const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); patternHost = escapeRegExp(patternHost); const regex = new RegExp(`(^|\\.)${patternHost}$`); if (regex.test(urlHost)) { 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 ProcessedElementsCache = { _processedElements: new WeakSet(), isProcessed(element) { if (!Utils || !Utils.isElement) return false; if (!Utils.isElement(element)) return false; return this._processedElements.has(element); }, markAsProcessed(element) { if (!Utils || !Utils.isElement) return; if (!Utils.isElement(element)) return; this._processedElements.add(element); }, clear() { this._processedElements = new WeakSet(); } }; const MODULE_NAMES = { removeInlineScripts: '移除内嵌脚本', removeExternalScripts: '移除外联脚本', blockDynamicScripts: '拦截动态脚本', interceptThirdParty: '拦截第三方资源', manageCSP: 'CSP策略管理', scriptBlacklistMode: '脚本黑名单模式' }; 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); }, 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) { urlCache.urlCheckCache.set(cacheKey, false, CONFIG.CACHE_TTL); return false; } }, 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.thirdPartyStrictMode; }, 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)); }, isContainerEmpty(container, ignoreProcessedFlag = true) { if (!this.isElement(container)) return false; if (container.children.length === 0 && container.textContent.trim() === '') { return this.isSuspiciousAdContainer(container); } let hasVisibleContent = false; for (const child of container.childNodes) { if (child.nodeType === Node.TEXT_NODE && child.textContent.trim().length > 0) { hasVisibleContent = true; break; } if (child.nodeType === Node.ELEMENT_NODE) { const el = child; if (ignoreProcessedFlag && ProcessedElementsCache.isProcessed(el)) continue; const style = getComputedStyle(el); if (style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0') { if (el.tagName === 'IMG' || el.tagName === 'VIDEO' || el.tagName === 'CANVAS' || (el.textContent && el.textContent.trim().length > 0)) { hasVisibleContent = true; break; } if (style.opacity !== '0' && style.visibility !== 'hidden' && el.offsetWidth > 0 && el.offsetHeight > 0 && el.tagName !== 'BR' && el.tagName !== 'HR') { hasVisibleContent = true; break; } } } } return !hasVisibleContent; }, isSuspiciousAdContainer(container) { if (!this.isElement(container)) return false; const style = getComputedStyle(container); return ( (style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent') || style.backgroundImage !== 'none' || style.borderWidth !== '0px' || style.boxShadow !== 'none' || style.paddingTop !== '0px' || style.paddingBottom !== '0px' || style.marginTop !== '0px' || style.marginBottom !== '0px' || (parseFloat(style.width) > CONFIG.RESIDUAL_MIN_WIDTH && parseFloat(style.height) > CONFIG.RESIDUAL_MIN_HEIGHT) || style.position === 'relative' || style.position === 'absolute' || style.position === 'fixed' || style.position === 'sticky' ); }, quickAdFilter(container) { if (!this.isElement(container)) return false; if (ProcessedElementsCache.isProcessed(container)) return false; if (this.isUIElement(container)) return false; if (!currentConfig.residualCleanupEnabled) return false; if (!this.isContainerEmpty(container, true)) return false; return this.isSuspiciousAdContainer(container); }, 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); } }; }, isParentProcessed(element) { let parent = element.parentElement; while (parent) { if (ProcessedElementsCache.isProcessed(parent)) return true; parent = parent.parentElement; } return false; }, getActiveBlacklistSet() { const set = new Set(currentConfig.scriptBlacklist); if (currentConfig.builtinBlacklistEnabled) { BUILTIN_BLACKLIST_KEYWORDS.forEach(k => { if (!currentConfig.removedBuiltinKeywords.has(k)) set.add(k); }); } return set; }, getActiveBlacklistArray() { return Array.from(this.getActiveBlacklistSet()); }, 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, 500)}` : `SCRIPT_CONTENT: ${this.truncateString(element.textContent, 500)}`; if (tagName === 'IFRAME') return `IFRAME_SRC: ${this.truncateString(element.src, 500)}`; if (tagName === 'IMG') return src ? `IMG_SRC: ${this.truncateString(src, 500)}` : null; if (tagName === 'A') return src ? `A_HREF: ${this.truncateString(src, 500)}` : null; if (tagName === 'LINK' && element.rel === 'stylesheet' && element.href) return `CSS_HREF: ${this.truncateString(element.href, 500)}`; if (tagName === 'STYLE') return `STYLE_CONTENT: ${this.truncateString(element.textContent, 500)}`; if (tagName === 'EMBED') return src ? `EMBED_SRC: ${this.truncateString(src, 500)}` : null; if (tagName === 'OBJECT') return src ? `OBJECT_DATA: ${this.truncateString(src, 500)}` : 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(), 500)}`; if (reasonType.detail.startsWith('URL:')) return `${reasonType.type || 'INTERCEPTED'}_URL: ${this.truncateString(reasonType.detail.substring(5).trim(), 500)}`; if (reasonType.type === 'EVAL') return `EVAL_HASH: ${generateContentHash(reasonType.detail, 500)}`; if (reasonType.type === 'FUNCTION_CONSTRUCTOR') return `FUNCTION_HASH: ${generateContentHash(reasonType.detail, 500)}`; if (reasonType.type === 'DOCUMENT_WRITE') return `DOCUMENT_WRITE_HASH: ${generateContentHash(reasonType.detail, 500)}`; if (reasonType.type === 'SETTIMEOUT') return `SETTIMEOUT_HASH: ${generateContentHash(reasonType.detail, 500)}`; if (reasonType.type === 'SETINTERVAL') return `SETINTERVAL_HASH: ${generateContentHash(reasonType.detail, 500)}`; if (reasonType.type === 'REQUESTANIMATIONFRAME') return `REQUESTANIMATIONFRAME_HASH: ${generateContentHash(reasonType.detail, 500)}`; if (reasonType.type === 'THIRD_PARTY') { const urlMatch = reasonType.detail.match(/(https?:\/\/[^\s]+)/); if (urlMatch) return `THIRD_PARTY_URL: ${this.truncateString(urlMatch[1], 500)}`; return `THIRD_PARTY_DETAIL: ${this.truncateString(reasonType.detail, 500)}`; } if (reasonType.type === 'SCRIPT_BLACKLIST') return `BLACKLIST: ${this.truncateString(reasonType.detail, 500)}`; if (reasonType.type === '内联事件') return `INLINE_EVENT: ${reasonType.detail}`; if (reasonType.type === 'javascript URL') return `JAVASCRIPT_URL: ${reasonType.detail}`; return `LOG_DETAIL: ${this.truncateString(reasonType.detail, 500)}`; } return null; } }; function shouldBlockResource(url) { if (!url) return false; if (urlCache.isWhitelisted(url, currentConfig.thirdPartyWhitelist)) return false; for (const keyword of currentConfig.keywordWhitelist) { if (url.includes(keyword)) return false; } return Utils.isThirdParty(url, Utils.getBlockParentSubDomainsSetting()); } const LogManager = { logs: [], maxLogs: CONFIG.LOG_MAX, loggedContentIdentifiers: new LRUCache(CONFIG.LOG_MAX, CONFIG.LOG_IDENTIFIER_TTL), add(moduleKey, element, reason) { const anyModuleEnabled = Object.values(currentConfig.modules).some(v => v === true); if (!anyModuleEnabled) return; if (!Utils.isElement(element) && element !== null && typeof reason !== 'object') return; if (Whitelisting.isElementWhitelisted(element) || Whitelisting.isReasonWhitelisted(reason)) return; let elementIdentifier = '[未知元素]', interceptedContent = '[无法获取内容]', contentIdentifier = null, resourceDomain = ''; if (reason && typeof reason.detail === 'string' && ( reason.type === '内联事件' || reason.type === 'javascript URL' || reason.type === 'EVAL' || reason.type === 'FUNCTION_CONSTRUCTOR' || reason.type === 'DOCUMENT_WRITE' || reason.type === 'SETTIMEOUT' || reason.type === 'SETINTERVAL' || reason.type === 'REQUESTANIMATIONFRAME' || reason.type === 'THIRD_PARTY' || reason.type === 'SCRIPT_BLACKLIST' || reason.type === 'THIRD_PARTY_SCAN' )) { interceptedContent = Utils.truncateString(reason.detail, 500); elementIdentifier = reason.type ? `[${reason.type}]` : '[未知类型]'; if (reason.type === 'EVAL' || reason.type === 'FUNCTION_CONSTRUCTOR' || reason.type === 'DOCUMENT_WRITE' || reason.type === 'SETTIMEOUT' || reason.type === 'SETINTERVAL' || reason.type === 'REQUESTANIMATIONFRAME') { contentIdentifier = Utils.getContentIdentifier(null, { type: reason.type, detail: reason.rawDetail || reason.detail }); } else { 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) { /* ignore */ } } } else 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, 500)}`; 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, 500); if (src) resourceDomain = Utils.getResourceHostname(src) || ''; } else if (tagName === 'A') { interceptedContent = Utils.truncateString(element.href || '', 500); if (element.href) resourceDomain = Utils.getResourceHostname(element.href) || ''; } else if (tagName === 'LINK') { interceptedContent = Utils.truncateString(element.href || '', 500); if (element.href) resourceDomain = Utils.getResourceHostname(element.href) || ''; } else if (tagName === 'STYLE') { interceptedContent = Utils.truncateString(element.textContent, 500); } else if (tagName === 'EMBED') { interceptedContent = Utils.truncateString(element.src || '', 500); if (element.src) resourceDomain = Utils.getResourceHostname(element.src) || ''; } else if (tagName === 'OBJECT') { interceptedContent = Utils.truncateString(element.data || '', 500); if (element.data) resourceDomain = Utils.getResourceHostname(element.data) || ''; } else { interceptedContent = Utils.truncateString(element.outerHTML, 500); } } else if (reason && typeof reason.detail === 'string') { interceptedContent = Utils.truncateString(reason.detail, 500); elementIdentifier = reason.type ? `[${reason.type}]` : '[未知类型]'; if (reason.type === 'EVAL' || reason.type === 'FUNCTION_CONSTRUCTOR' || reason.type === 'DOCUMENT_WRITE' || reason.type === 'SETTIMEOUT' || reason.type === 'SETINTERVAL' || reason.type === 'REQUESTANIMATIONFRAME') { contentIdentifier = Utils.getContentIdentifier(null, { type: reason.type, detail: reason.rawDetail || reason.detail }); } else { 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) { /* ignore */ } } } if (!contentIdentifier) return; const existingIndex = this.logs.findIndex(l => l.contentIdentifier === contentIdentifier); if (existingIndex !== -1) { this.logs.splice(existingIndex, 1); } else if (this.loggedContentIdentifiers.has(contentIdentifier)) { return; } this.logs.push({ id: this.logs.length + 1, moduleKey, module: MODULE_NAMES[moduleKey] || moduleKey, element: elementIdentifier, content: interceptedContent, domain: resourceDomain, timestamp: Date.now(), contentIdentifier }); 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 ci = Utils.getContentIdentifier(element); if (ci && currentConfig.whitelist.has(ci)) return true; if (currentConfig.modules.interceptThirdParty) { const hostname = Utils.getResourceHostname(element.src || element.href || element.action || element.data || ''); if (hostname) { const ru = element.src || element.href || element.action || element.data || ''; if (urlCache.isWhitelisted(ru, currentConfig.thirdPartyWhitelist)) return true; } } if (currentConfig.keywordWhitelist.size > 0) { const sc = element.textContent || ''; const src = element.src || element.href || element.action || element.data || ''; for (const kw of currentConfig.keywordWhitelist) { if (!kw) continue; if (sc.includes(kw) || src.includes(kw)) return true; } } return false; }, isReasonWhitelisted(reason) { if (!reason || typeof reason.detail !== 'string') return false; let ci; if (reason.type === 'EVAL' || reason.type === 'FUNCTION_CONSTRUCTOR' || reason.type === 'DOCUMENT_WRITE' || reason.type === 'SETTIMEOUT' || reason.type === 'SETINTERVAL' || reason.type === 'REQUESTANIMATIONFRAME') { ci = Utils.getContentIdentifier(null, { type: reason.type, detail: reason.rawDetail || reason.detail }); } else { ci = Utils.getContentIdentifier(null, reason); } if (ci && currentConfig.whitelist.has(ci)) return true; if (currentConfig.modules.interceptThirdParty) { const um = reason.detail.match(/https?:\/\/[^\s]+/); if (um) { if (urlCache.isWhitelisted(um[0], currentConfig.thirdPartyWhitelist)) return true; } } if (currentConfig.keywordWhitelist.size > 0) { for (const kw of currentConfig.keywordWhitelist) { if (!kw) continue; if (reason.detail.includes(kw)) return true; } } return false; }, isCodeWhitelisted(code, type) { if (typeof code !== 'string' || code.trim() === '') return false; if (currentConfig.keywordWhitelist.size > 0) { for (const kw of currentConfig.keywordWhitelist) { if (!kw) continue; if (code.includes(kw)) return true; } } const ci = Utils.getContentIdentifier(null, { type, detail: code }); if (ci && currentConfig.whitelist.has(ci)) return true; return false; }, add(contentIdentifier) { if (!contentIdentifier || contentIdentifier.trim() === '') return; currentConfig.whitelist.add(contentIdentifier); ConfigUpdater.saveNow(); }, addKeyword(keyword) { if (!keyword || keyword.trim() === '') return; currentConfig.keywordWhitelist.add(keyword.trim()); ConfigUpdater.saveNow(); }, removeKeywordsMatchingDomain(domain) { let changed = false; const toRemove = []; for (const kw of currentConfig.keywordWhitelist) { if (domain.includes(kw)) toRemove.push(kw); } toRemove.forEach(k => { currentConfig.keywordWhitelist.delete(k); changed = true; }); if (changed) ConfigUpdater.saveNow(); }, clearAllWhitelists() { currentConfig.whitelist.clear(); currentConfig.keywordWhitelist.clear(); currentConfig.thirdPartyWhitelist = []; ConfigUpdater.saveNow(); } }; function getLogWhitelistStatus(log) { if (currentConfig.whitelist.has(log.contentIdentifier)) return 'whitelisted'; const kws = Array.from(currentConfig.keywordWhitelist); if (kws.some(kw => (log.content && log.content.includes(kw)) || (log.domain && log.domain.includes(kw)))) return 'keyword-whitelisted'; if (log.domain && urlCache.isWhitelisted(log.domain, currentConfig.thirdPartyWhitelist)) return 'whitelisted'; return ''; } function isThirdPartyUrl(url) { if (!url || typeof url !== 'string') return false; if (url.startsWith('#') || url.startsWith('javascript:')) return false; try { const targetUrl = new URL(url, _location.href); const currentHost = _location.hostname; if (targetUrl.hostname === currentHost) return false; return urlCache.isThirdPartyHost(targetUrl.hostname, currentHost, !!currentConfig.thirdPartyStrictMode); } catch (e) { return false; } } if (_document.designMode === 'on' || _document.documentElement.style.pointerEvents === 'none') { _document.designMode = 'off'; _document.documentElement.style.pointerEvents = ''; } let activePanels = new _Set(); let strongBlockingEnabled = false; let blockingTimer = null; const _beforeunloadHandler = function (e) { e.preventDefault(); e.returnValue = '系统可能不会保存您所做的更改。'; return e.returnValue; }; const _errorHandler = function (e) { if (strongBlockingEnabled) { disableStrongBlocking(); activePanels.clear(); } }; function enableStrongBlocking() { if (strongBlockingEnabled) return; _globals.addEventListener('beforeunload', _beforeunloadHandler); _globals.addEventListener('error', _errorHandler, true); strongBlockingEnabled = true; if (blockingTimer) _clearTimeout(blockingTimer); blockingTimer = _setTimeout(() => { if (activePanels.size > 0) { activePanels.clear(); disableStrongBlocking(); } }, CONFIG.STRONG_BLOCK_TIMEOUT); } function disableStrongBlocking() { if (!strongBlockingEnabled) return; _globals.removeEventListener('beforeunload', _beforeunloadHandler); _globals.removeEventListener('error', _errorHandler, true); strongBlockingEnabled = false; if (blockingTimer) { _clearTimeout(blockingTimer); blockingTimer = null; } } function setupNavigationBlocking(panelId) { activePanels.add(panelId); if (activePanels.size === 1) { enableStrongBlocking(); if (currentConfig.modules.blockDynamicScripts) DynamicScriptInterceptor.disable(); } } function teardownNavigationBlocking(panelId) { activePanels.delete(panelId); if (activePanels.size === 0) { disableStrongBlocking(); if (currentConfig.modules.blockDynamicScripts) DynamicScriptInterceptor.enable(); } } const RedirectBlocker = { _initialized: false, init() { if (this._initialized) return; if (!currentConfig.redirectBlockerEnabled) return; this._initialized = true; this._interceptLocation(); this._interceptWindowOpen(); this._interceptHistory(); this._interceptDocumentDomain(); this._interceptServiceWorker(); this._interceptPostMessage(); this._interceptFormSubmit(); this._interceptAnchorClick(); this._interceptNavigationAPI(); this._interceptDocumentWriteTiming(); this._interceptSetTimeoutRedirect(); this._interceptIframeSrc(); this._interceptBaseHref(); this._interceptEmbedObjectArea(); this._observeMetaAndPrefetch(); }, _interceptLocation() { try { const d = Object.getOwnPropertyDescriptor(Location.prototype, 'href'); if (d && d.set) Object.defineProperty(Location.prototype, 'href', { get: d.get, set(v) { if (isThirdPartyUrl(v)) return; d.set.call(this, v); }, enumerable: true, configurable: false }); } catch (e) { /* ignore */ } try { const o = Location.prototype.assign; Object.defineProperty(Location.prototype, 'assign', { value(u) { if (isThirdPartyUrl(u)) return; return o.call(this, u); }, writable: false, configurable: false }); } catch (e) { /* ignore */ } try { const o = Location.prototype.replace; Object.defineProperty(Location.prototype, 'replace', { value(u) { if (isThirdPartyUrl(u)) return; return o.call(this, u); }, writable: false, configurable: false }); } catch (e) { /* ignore */ } }, _interceptWindowOpen() { try { const o = window.open; Object.defineProperty(window, 'open', { value(...a) { if (isThirdPartyUrl(a[0])) return null; return o.apply(this, a); }, writable: false, configurable: false }); } catch (e) { /* ignore */ } }, _interceptHistory() { try { const op = history.pushState; const or2 = history.replaceState; Object.defineProperty(history, 'pushState', { value(s, t, u) { if (isThirdPartyUrl(u)) return; if (typeof resetAllCachesAndStates === 'function') resetAllCachesAndStates(); return op.apply(this, arguments); }, writable: false, configurable: false }); Object.defineProperty(history, 'replaceState', { value(s, t, u) { if (isThirdPartyUrl(u)) return; if (typeof resetAllCachesAndStates === 'function') resetAllCachesAndStates(); return or2.apply(this, arguments); }, writable: false, configurable: false }); } catch (e) { /* ignore */ } _globals.addEventListener('popstate', function () { if (typeof resetAllCachesAndStates === 'function') resetAllCachesAndStates(); }, { capture: true }); }, _interceptDocumentDomain() { try { const d = Object.getOwnPropertyDescriptor(Document.prototype, 'domain'); if (d && d.set) Object.defineProperty(Document.prototype, 'domain', { get: d.get, set() { return; }, enumerable: true, configurable: false }); } catch (e) { /* ignore */ } }, _interceptServiceWorker() { try { if (navigator.serviceWorker) { const o = navigator.serviceWorker.register; Object.defineProperty(navigator.serviceWorker, 'register', { value() { return Promise.reject(new Error('Blocked by adblocker')); }, writable: false, configurable: false }); } } catch (e) { /* ignore */ } }, _interceptPostMessage() { try { const o = window.postMessage; Object.defineProperty(window, 'postMessage', { value(m, t, tr) { if (t === '*' || (t && t !== location.origin && t !== '/')) return; return o.call(this, m, t, tr); }, writable: false, configurable: false }); } catch (e) { /* ignore */ } }, _interceptFormSubmit() { try { const o = HTMLFormElement.prototype.submit; Object.defineProperty(HTMLFormElement.prototype, 'submit', { value() { const a = this.getAttribute('action'); if (a && isThirdPartyUrl(a)) return; return o.call(this); }, writable: false, configurable: false }); } catch (e) { /* ignore */ } try { const fp = HTMLFormElement.prototype; const ad = Object.getOwnPropertyDescriptor(fp, 'action'); if (ad && ad.set && ad.configurable) { Object.defineProperty(fp, 'action', { configurable: true, enumerable: true, get() { return ad.get.call(this); }, set(v) { if (!v || v.trim() === '') { ad.set.call(this, v); return; } if (isThirdPartyUrl(v)) return; ad.set.call(this, v); } }); } document.addEventListener('submit', function (e) { const f = e.target; if (f && f.tagName === 'FORM') { const a = f.getAttribute('action'); if (a && isThirdPartyUrl(a)) { e.preventDefault(); e.stopImmediatePropagation(); return false; } } }, true); } catch (e) { /* ignore */ } }, _interceptAnchorClick() { document.addEventListener('click', function (e) { const t = e.target.closest('a'); if (t) { const h = t.getAttribute('href') || t.href; if (isThirdPartyUrl(h)) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); return false; } } }, true); try { const o = HTMLAnchorElement.prototype.click; Object.defineProperty(HTMLAnchorElement.prototype, 'click', { value() { const h = this.getAttribute('href') || this.href; if (isThirdPartyUrl(h)) return; return o.call(this); }, writable: false, configurable: false }); } catch (e) { /* ignore */ } }, _interceptNavigationAPI() { try { if (window.navigation && window.navigation.navigate) { const o = window.navigation.navigate; Object.defineProperty(window.navigation, 'navigate', { value(u) { if (isThirdPartyUrl(u)) return { committed: Promise.reject(), finished: Promise.reject() }; return o.apply(this, arguments); }, writable: false, configurable: false }); } } catch (e) { /* ignore */ } }, _interceptDocumentWriteTiming() { try { const ow = document.write; const owln = document.writeln; document.write = function (...a) { if (document.readyState !== 'loading') return; return ow.apply(this, a); }; document.writeln = function (...a) { if (document.readyState !== 'loading') return; return owln.apply(this, a); }; } catch (e) { /* ignore */ } }, _interceptSetTimeoutRedirect() { try { const o = window.setTimeout; window.setTimeout = function (cb, d, ...a) { if (typeof cb === 'function') { if (/(?:location\s*\.\s*href|location\s*=|window\s*\.\s*open)\s*=/i.test(cb.toString())) return -1; } return o.call(this, cb, d, ...a); }; } catch (e) { /* ignore */ } }, _interceptIframeSrc() { try { const ip = HTMLIFrameElement.prototype; const d = Object.getOwnPropertyDescriptor(ip, 'src'); if (d && d.set && d.configurable) Object.defineProperty(ip, 'src', { configurable: true, enumerable: true, get() { return d.get.call(this); }, set(v) { if (isThirdPartyUrl(v)) return; d.set.call(this, v); } }); const fp = HTMLFrameElement.prototype; const d2 = Object.getOwnPropertyDescriptor(fp, 'src'); if (d2 && d2.set && d2.configurable) Object.defineProperty(fp, 'src', { configurable: true, enumerable: true, get() { return d2.get.call(this); }, set(v) { if (isThirdPartyUrl(v)) return; d2.set.call(this, v); } }); } catch (e) { /* ignore */ } }, _interceptBaseHref() { try { new _MutationObserver((ms) => { for (const m of ms) { if (m.type === 'childList') m.addedNodes.forEach(n => { if (n.nodeType === Node.ELEMENT_NODE && n.tagName === 'BASE') { const h = n.getAttribute('href'); if (h && isThirdPartyUrl(h)) n.removeAttribute('href'); } }); else if (m.type === 'attributes' && m.attributeName === 'href' && m.target.tagName === 'BASE') { const h = m.target.getAttribute('href'); if (h && isThirdPartyUrl(h)) m.target.removeAttribute('href'); } } }).observe(_document.documentElement || _document, { childList: true, subtree: true, attributes: true, attributeFilter: ['href'] }); } catch (e) { /* ignore */ } }, _interceptEmbedObjectArea() { try { const ap = HTMLAreaElement.prototype; const ad = Object.getOwnPropertyDescriptor(ap, 'href'); if (ad && ad.set && ad.configurable) Object.defineProperty(ap, 'href', { configurable: true, enumerable: true, get() { return ad.get.call(this); }, set(v) { if (isThirdPartyUrl(v)) return; ad.set.call(this, v); } }); const ep = HTMLEmbedElement.prototype; const ed = Object.getOwnPropertyDescriptor(ep, 'src'); if (ed && ed.set && ed.configurable) Object.defineProperty(ep, 'src', { configurable: true, enumerable: true, get() { return ed.get.call(this); }, set(v) { if (isThirdPartyUrl(v)) return; ed.set.call(this, v); } }); const op = HTMLObjectElement.prototype; const od = Object.getOwnPropertyDescriptor(op, 'data'); if (od && od.set && od.configurable) Object.defineProperty(op, 'data', { configurable: true, enumerable: true, get() { return od.get.call(this); }, set(v) { if (isThirdPartyUrl(v)) return; od.set.call(this, v); } }); } catch (e) { /* ignore */ } }, _observeMetaAndPrefetch() { try { new _MutationObserver((ms) => { for (const m of ms) { if (!m.addedNodes) continue; m.addedNodes.forEach((n) => { if (!(n instanceof Element)) return; if (n.tagName === 'META' && /refresh/i.test(n.getAttribute('http-equiv')) && /url\s*=/i.test(n.getAttribute('content') || '')) n.remove(); if (n.tagName === 'LINK' && (n.rel === 'prefetch' || n.rel === 'prerender' || n.rel === 'preload')) { const h = n.getAttribute('href'); if (h && isThirdPartyUrl(h)) n.remove(); } if (n.querySelectorAll) n.querySelectorAll('meta[http-equiv="refresh"]').forEach(m2 => m2.remove()); }); } }).observe(_document.documentElement || _document, { childList: true, subtree: true }); } catch (e) { /* ignore */ } } }; RedirectBlocker.init(); const DynamicScriptInterceptor = { _enabled: false, originalEval: null, originalFunction: null, originalFunctionConstructorDescriptor: null, originalSetTimeout: null, originalSetInterval: null, originalClearTimeout: null, originalClearInterval: null, originalRequestAnimationFrame: null, originalCancelAnimationFrame: null, originalDocumentWrite: null, originalDocumentWriteln: null, 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; this.originalDocumentWrite = _document.write; this.originalDocumentWriteln = _document.writeln; const self = this; try { _globals.eval = function (code) { if (typeof code === 'string') { if (Whitelisting.isCodeWhitelisted(code, 'EVAL')) return self.originalEval.call(this, code); const ci = Utils.getContentIdentifier(null, { type: 'EVAL', detail: code }); if (ci && !currentConfig.whitelist.has(ci)) { LogManager.add('blockDynamicScripts', null, { type: 'EVAL', detail: Utils.truncateString(code, 500), rawDetail: code }); return undefined; } } return self.originalEval.call(this, code); }; } catch (e) { /* ignore */ } try { this.originalFunctionConstructorDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'constructor'); _globals.Function = new _Proxy(this.originalFunction, { construct(target, args, newTarget) { const code = (args.length > 0) ? String(args[args.length - 1]) : ''; if (typeof code === 'string') { if (Whitelisting.isCodeWhitelisted(code, 'FUNCTION_CONSTRUCTOR')) return Reflect.construct(target, args, newTarget || target); const ci = Utils.getContentIdentifier(null, { type: 'FUNCTION_CONSTRUCTOR', detail: code }); if (ci && !currentConfig.whitelist.has(ci)) { LogManager.add('blockDynamicScripts', null, { type: 'FUNCTION_CONSTRUCTOR', detail: Utils.truncateString(code, 500), rawDetail: code }); return Reflect.construct(target, ['return;'], newTarget || target); } } return Reflect.construct(target, args, newTarget || target); }, apply(target, thisArg, args) { const code = (args.length > 0) ? String(args[args.length - 1]) : ''; if (typeof code === 'string') { if (Whitelisting.isCodeWhitelisted(code, 'FUNCTION_CONSTRUCTOR')) return Reflect.apply(target, thisArg, args); const ci = Utils.getContentIdentifier(null, { type: 'FUNCTION_CONSTRUCTOR', detail: code }); if (ci && !currentConfig.whitelist.has(ci)) { LogManager.add('blockDynamicScripts', null, { type: 'FUNCTION_CONSTRUCTOR', detail: Utils.truncateString(code, 500), rawDetail: code }); return Reflect.apply(target, thisArg, ['return;']); } } return Reflect.apply(target, thisArg, args); } }); try { Object.defineProperty(Function.prototype, 'constructor', { get: () => _globals.Function, configurable: true }); } catch (e) { /* ignore */ } } catch (e) { /* ignore */ } const checkCallback = (callback, type) => { if (typeof callback === 'string') { if (Whitelisting.isCodeWhitelisted(callback, type)) return { blocked: false }; const ci = Utils.getContentIdentifier(null, { type, detail: callback }); if (ci && !currentConfig.whitelist.has(ci)) { LogManager.add('blockDynamicScripts', null, { type, detail: Utils.truncateString(callback, 500), rawDetail: callback }); return { blocked: true }; } return { blocked: false }; } else if (typeof callback === 'function') { const fs = callback.toString(); if (fs.includes('eval') || fs.includes('Function')) { const ci = Utils.getContentIdentifier(null, { type, detail: fs }); if (ci && !currentConfig.whitelist.has(ci)) { LogManager.add('blockDynamicScripts', null, { type, detail: Utils.truncateString(fs, 500), rawDetail: fs }); return { blocked: true }; } } return { blocked: false }; } return { blocked: false }; }; try { _globals.setTimeout = function (cb, d, ...a) { const r = checkCallback(cb, 'SETTIMEOUT'); if (r.blocked) return -1; return self.originalSetTimeout.call(this, cb, d, ...a); }; _globals.setInterval = function (cb, d, ...a) { const r = checkCallback(cb, 'SETINTERVAL'); if (r.blocked) return -1; return self.originalSetInterval.call(this, cb, d, ...a); }; _globals.clearTimeout = function (id) { if (id === -1) return; return self.originalClearTimeout.call(this, id); }; _globals.clearInterval = function (id) { if (id === -1) return; return self.originalClearInterval.call(this, id); }; _globals.requestAnimationFrame = function (cb) { const r = checkCallback(cb, 'REQUESTANIMATIONFRAME'); if (r.blocked) return -1; return self.originalRequestAnimationFrame.call(this, cb); }; _globals.cancelAnimationFrame = function (id) { if (id === -1) return; return self.originalCancelAnimationFrame.call(this, id); }; } catch (e) { /* ignore */ } try { _document.write = function (...a) { const c = a.join(''); if (typeof c === 'string') { if (Whitelisting.isCodeWhitelisted(c, 'DOCUMENT_WRITE')) return self.originalDocumentWrite.apply(this, a); const ci = Utils.getContentIdentifier(null, { type: 'DOCUMENT_WRITE', detail: c }); if (ci && !currentConfig.whitelist.has(ci)) { LogManager.add('blockDynamicScripts', null, { type: 'DOCUMENT_WRITE', detail: Utils.truncateString(c, 500), rawDetail: c }); return; } } return self.originalDocumentWrite.apply(this, a); }; _document.writeln = function (...a) { const c = a.join(''); if (typeof c === 'string') { if (Whitelisting.isCodeWhitelisted(c, 'DOCUMENT_WRITELN')) return self.originalDocumentWriteln.apply(this, a); const ci = Utils.getContentIdentifier(null, { type: 'DOCUMENT_WRITE', detail: c }); if (ci && !currentConfig.whitelist.has(ci)) { LogManager.add('blockDynamicScripts', null, { type: 'DOCUMENT_WRITE', detail: Utils.truncateString(c, 500), rawDetail: c }); return; } } return self.originalDocumentWriteln.apply(this, a); }; } catch (e) { /* ignore */ } }, disable() { if (!this._enabled) return; this._enabled = false; try { _globals.eval = this.originalEval; } catch (e) { /* ignore */ } try { _globals.Function = this.originalFunction; if (this.originalFunctionConstructorDescriptor) Object.defineProperty(Function.prototype, 'constructor', this.originalFunctionConstructorDescriptor); else try { delete Function.prototype.constructor; } catch (e) { /* ignore */ } } catch (e) { /* ignore */ } try { _globals.setTimeout = this.originalSetTimeout; } catch (e) { /* ignore */ } try { _globals.setInterval = this.originalSetInterval; } catch (e) { /* ignore */ } try { _globals.clearTimeout = this.originalClearTimeout; } catch (e) { /* ignore */ } try { _globals.clearInterval = this.originalClearInterval; } catch (e) { /* ignore */ } try { _globals.requestAnimationFrame = this.originalRequestAnimationFrame; } catch (e) { /* ignore */ } try { _globals.cancelAnimationFrame = this.originalCancelAnimationFrame; } catch (e) { /* ignore */ } try { _document.write = this.originalDocumentWrite; } catch (e) { /* ignore */ } try { _document.writeln = this.originalDocumentWriteln; } catch (e) { /* ignore */ } this.originalEval = this.originalFunction = this.originalSetTimeout = this.originalSetInterval = null; this.originalClearTimeout = this.originalClearInterval = this.originalRequestAnimationFrame = this.originalCancelAnimationFrame = null; this.originalDocumentWrite = this.originalDocumentWriteln = null; } }; if (currentConfig.modules.blockDynamicScripts) DynamicScriptInterceptor.enable(); const ResidualCleaner = { _scanTimer: null, _dedupSet: new WeakSet(), observer: null, init() { const any = Object.values(currentConfig.modules).some(v => v === true); if (!any || !currentConfig.residualCleanupEnabled) { this.stop(); return; } this.setupMutationObserver(); this.initialScan(); this.startPeriodicScan(); }, stop() { if (this.observer) { this.observer.disconnect(); this.observer = null; } if (this._scanTimer !== null) { _cancelIdleCallback(this._scanTimer); this._scanTimer = null; } this._dedupSet = new WeakSet(); }, setupMutationObserver() { this.observer = new _MutationObserver((ms) => { for (const m of ms) { if (m.type === 'childList') { if (m.addedNodes.length > 0) for (const n of m.addedNodes) { if (n.nodeType === Node.ELEMENT_NODE && Utils.isElement(n)) this.checkAndCleanup(n); } if (m.removedNodes.length > 0 && m.target && Utils.isElement(m.target)) this.checkAndCleanup(m.target); } } }); this.observer.observe(_document.documentElement, { childList: true, subtree: true, attributes: false }); }, isTransparentOverlay(el) { if (!el || el.tagName !== 'A' || this._dedupSet.has(el)) return false; const s = getComputedStyle(el); if (el.offsetWidth < 30 || el.offsetHeight < 30) return false; if (s.position !== 'absolute' && s.position !== 'fixed') return false; const z = parseInt(s.zIndex); if (isNaN(z) || z < 100) return false; return !Array.from(el.childNodes).some(c => { if (c.nodeType === Node.TEXT_NODE && c.textContent.trim().length > 0 && s.color !== 'transparent' && parseFloat(s.opacity) > 0.1) return true; if (c.nodeType === Node.ELEMENT_NODE && c.tagName === 'IMG' && c.naturalWidth > 5 && c.naturalHeight > 5) return true; return false; }); }, cleanEmptyParents(parent) { if (!parent || parent === _document.body || parent === _document.documentElement || !Utils.isElement(parent) || this._dedupSet.has(parent)) return; if (Array.from(parent.childNodes).some(c => (c.nodeType === Node.ELEMENT_NODE && !ProcessedElementsCache.isProcessed(c)) || (c.nodeType === Node.TEXT_NODE && c.textContent.trim().length > 0))) return; if (this.isStrictEmpty(parent) && Utils.isSuspiciousAdContainer(parent)) { this._dedupSet.add(parent); const np = parent.parentElement; parent.remove(); ProcessedElementsCache.markAsProcessed(parent); this.cleanEmptyParents(np); } }, isStrictEmpty(container) { if (!Utils.isElement(container)) return false; if (container.getAttribute && container.getAttribute('data-adblock-safe') === 'true') return false; let hasReal = false; for (let i = 0; i < container.childNodes.length; i++) { const child = container.childNodes[i]; if (child.nodeType === Node.ELEMENT_NODE && ProcessedElementsCache.isProcessed(child)) continue; if (child.nodeType === Node.TEXT_NODE) { if (child.textContent.trim().length > 1) { if (!child.parentElement) continue; const ps = getComputedStyle(child.parentElement); if (ps.color !== 'transparent' && parseFloat(ps.opacity) > 0.1) { hasReal = true; break; } } } else if (child.nodeType === Node.ELEMENT_NODE) { const el = child; const s = getComputedStyle(el); if (s.display === 'none' || s.visibility === 'hidden' || s.opacity === '0') continue; if (el.tagName === 'IMG' && ((el.naturalWidth <= 5 && el.naturalHeight <= 5) || (el.offsetWidth <= 5 && el.offsetHeight <= 5))) continue; if (el.offsetWidth > 10 && el.offsetHeight > 10) { if (el.tagName === 'A') { let hasLink = false; for (let j = 0; j < el.childNodes.length; j++) { const c = el.childNodes[j]; if (c.nodeType === Node.TEXT_NODE && c.textContent.trim().length > 0 && s.color !== 'transparent' && parseFloat(s.opacity) > 0.1) { hasLink = true; break; } if (c.nodeType === Node.ELEMENT_NODE) { if (c.tagName === 'IMG' && c.naturalWidth > 5 && c.naturalHeight > 5) { hasLink = true; break; } if (c.offsetWidth > 10 && c.offsetHeight > 10 && c.tagName !== 'BR' && c.tagName !== 'HR' && c.tagName !== 'A') { hasLink = true; break; } } } if (!hasLink) continue; } hasReal = true; break; } } } return !hasReal; }, checkAndCleanup(element) { if (!element || !Utils.isElement(element) || this._dedupSet.has(element) || element === _document.body || element === _document.documentElement) return; if (this.isTransparentOverlay(element)) { this._dedupSet.add(element); const p = element.parentElement; element.remove(); ProcessedElementsCache.markAsProcessed(element); this.cleanEmptyParents(p); return; } const w = element.offsetWidth; const h = element.offsetHeight; if (w > 0 && w < CONFIG.RESIDUAL_MIN_WIDTH && h > 0 && h < CONFIG.RESIDUAL_MIN_HEIGHT) return; if (!currentConfig.residualCleanupEnabled) return; if (this.isStrictEmpty(element)) { const s = getComputedStyle(element); const isFH = s.height !== 'auto' && parseFloat(s.height) > 50; const isHZ = parseInt(s.zIndex) > 600; const isAF = s.position === 'absolute' || s.position === 'fixed'; if (isFH || isAF || isHZ || Utils.isSuspiciousAdContainer(element)) { this._dedupSet.add(element); this.cleanupContainer(element, isAF || isHZ); } } }, cleanupContainer(container, forceHide = false) { if (!container || !Utils.isElement(container) || !container.isConnected) return; if (forceHide) { container.style.setProperty('display', 'none', 'important'); container.style.setProperty('visibility', 'hidden', 'important'); container.style.setProperty('pointer-events', 'none', 'important'); container.style.setProperty('height', '0px', 'important'); container.style.setProperty('overflow', 'hidden', 'important'); let p = container.parentElement; let d = 0; while (p && d < 3 && p !== _document.body && p !== _document.documentElement) { if (!Utils.isElement(p)) break; p.style.setProperty('pointer-events', 'none', 'important'); d++; if (Array.from(p.childNodes).some(c => (c.nodeType === Node.ELEMENT_NODE && !ProcessedElementsCache.isProcessed(c)) || (c.nodeType === Node.TEXT_NODE && c.textContent.trim().length > 0))) break; p = p.parentElement; } ProcessedElementsCache.markAsProcessed(container); } else { const p = container.parentElement; container.remove(); ProcessedElementsCache.markAsProcessed(container); this.cleanEmptyParents(p); } }, initialScan() { const links = _document.querySelectorAll('a'); for (let i = 0; i < links.length; i++) { if (this.isTransparentOverlay(links[i])) { this._dedupSet.add(links[i]); const p = links[i].parentElement; links[i].remove(); ProcessedElementsCache.markAsProcessed(links[i]); this.cleanEmptyParents(p); } } const els = Array.from(_document.querySelectorAll('div, span, section, aside, iframe')); const toR = []; const toH = []; for (const el of els) { if (!el || !Utils.isElement(el) || this._dedupSet.has(el) || el === _document.body || el === _document.documentElement) continue; const w = el.offsetWidth; const h = el.offsetHeight; if (w > 0 && w < CONFIG.RESIDUAL_MIN_WIDTH && h > 0 && h < CONFIG.RESIDUAL_MIN_HEIGHT) continue; if (this.isStrictEmpty(el)) { const s = getComputedStyle(el); const isFH = s.height !== 'auto' && parseFloat(s.height) > 50; const isHZ = parseInt(s.zIndex) > 600; const isAF = s.position === 'absolute' || s.position === 'fixed'; if (isFH || isAF || isHZ || Utils.isSuspiciousAdContainer(el)) { this._dedupSet.add(el); if (isAF || isHZ) toH.push(el); else toR.push(el); } } } toR.forEach(el => { const p = el.parentElement; ProcessedElementsCache.markAsProcessed(el); el.remove(); this.cleanEmptyParents(p); }); toH.forEach(el => { ProcessedElementsCache.markAsProcessed(el); el.style.setProperty('display', 'none', 'important'); el.style.setProperty('height', '0px', 'important'); el.style.setProperty('overflow', 'hidden', 'important'); }); }, startPeriodicScan() { let last = 0; const loop = (dl) => { if (!currentConfig.residualCleanupEnabled) return; const now = Date.now(); if (now - last > 3000 && dl.timeRemaining() > 5) { let cnt = 0; const links = _document.querySelectorAll('a'); for (let i = 0; i < links.length && dl.timeRemaining() > 5 && cnt < 10; i++) { if (this.isTransparentOverlay(links[i])) { this._dedupSet.add(links[i]); const p = links[i].parentElement; links[i].remove(); ProcessedElementsCache.markAsProcessed(links[i]); this.cleanEmptyParents(p); cnt++; } } const els = _document.querySelectorAll('div, span, section, aside'); for (let i = 0; i < els.length && dl.timeRemaining() > 5 && cnt < 20; i++) { this.checkAndCleanup(els[i]); cnt++; } if (cnt > 0) last = now; } this._scanTimer = _requestIdleCallback(loop); }; this._scanTimer = _requestIdleCallback(loop); } }; const CSSUniversalHider = { _enabled: false, _observer: null, _intersectionObserver: null, _processedSet: new WeakSet(), _hideClass: 'adblock-universal-hidden', _styleElement: null, init() { currentConfig.cssUniversalHideEnabled ? this.enable() : this.disable(); }, enable() { if (this._enabled) return; this._enabled = true; this.injectStyle(); this._intersectionObserver = new _IntersectionObserver((es) => { es.forEach(e => { if (e.isIntersecting) { const el = e.target; this._intersectionObserver.unobserve(el); if (this.shouldHideElement(el)) this.hideElement(el); } }); }, { threshold: 0 }); this._observer = new _MutationObserver((ms) => { for (const m of ms) { if (m.type === 'childList' && m.addedNodes.length > 0) for (const n of m.addedNodes) { if (n.nodeType === 1) this.observeElement(n); } } }); this._observer.observe(_document.documentElement, { childList: true, subtree: true }); this.scanAndHide(); }, disable() { if (!this._enabled) return; this._enabled = false; if (this._observer) { this._observer.disconnect(); this._observer = null; } if (this._intersectionObserver) { this._intersectionObserver.disconnect(); this._intersectionObserver = null; } if (this._styleElement && this._styleElement.parentNode) { this._styleElement.parentNode.removeChild(this._styleElement); this._styleElement = null; } try { _document.querySelectorAll(`.${this._hideClass}`).forEach(el => el.classList.remove(this._hideClass)); } catch (e) { /* ignore */ } this._processedSet = new WeakSet(); }, injectStyle() { if (this._styleElement) return; const s = _document.createElement('style'); s.textContent = `.${this._hideClass} { display: none !important; visibility: hidden !important; opacity: 0 !important; pointer-events: none !important; position: absolute !important; left: -9999px !important; top: -9999px !important; width: 0 !important; height: 0 !important; overflow: hidden !important; z-index: -999 !important; }`; _document.head.appendChild(s); this._styleElement = s; }, observeElement(el) { if (!el || el.nodeType !== 1 || (el.getAttribute && el.getAttribute('data-adblock-safe') === 'true') || Utils.isUIElement(el) || this._processedSet.has(el)) return; this._intersectionObserver.observe(el); }, shouldHideElement(el) { if (!el || el.nodeType !== 1 || (el.getAttribute && el.getAttribute('data-adblock-safe') === 'true') || Utils.isUIElement(el) || this._processedSet.has(el)) return false; try { let z = parseInt(window.getComputedStyle(el).zIndex); if (isNaN(z)) z = 0; if (z > 600) return true; } catch (e) { /* ignore */ } return false; }, hideElement(el) { if (this.shouldHideElement(el)) { el.classList.add(this._hideClass); this._processedSet.add(el); } }, scanAndHide() { if (!this._enabled) return; try { _document.querySelectorAll('*').forEach(el => this.observeElement(el)); } catch (e) { /* ignore */ } } }; const ResourceCanceller = { cancelResourceLoading(element) { if (!Utils.isElement(element) || ProcessedElementsCache.isProcessed(element)) return; const t = element.tagName; if (t === 'IMG') { element.removeAttribute('src'); element.removeAttribute('srcset'); element.removeAttribute('data-src'); } else if (t === 'IFRAME') { element.removeAttribute('src'); element.style.display = 'none'; } else if (t === 'SCRIPT') element.removeAttribute('src'); else if (t === 'LINK' && element.rel === 'stylesheet') element.removeAttribute('href'); else if (t === 'STYLE') element.textContent = ''; else if (t === 'EMBED') element.removeAttribute('src'); else if (t === 'OBJECT') element.removeAttribute('data'); const p = element.parentElement; if (p && p !== _document.body && p !== _document.documentElement && Utils.isContainerEmpty(p, true) && Utils.isSuspiciousAdContainer(p)) ResidualCleaner.checkAndCleanup(p); if (element.parentNode) element.parentNode.removeChild(element); ProcessedElementsCache.markAsProcessed(element); } }; const TAG_HANDLERS = { SCRIPT: { srcAttr: 'src', inlineContent: true, check(el, mk, reason) { const ci = Utils.getContentIdentifier(el); if (ci && !currentConfig.whitelist.has(ci)) { LogManager.add(mk, el, reason); if (mk === 'removeExternalScripts' || mk === 'scriptBlacklistMode') ResourceCanceller.cancelResourceLoading(el); else if (mk === 'removeInlineScripts' && !el.src) el.remove(); ProcessedElementsCache.markAsProcessed(el); return true; } return false; } }, IFRAME: { srcAttr: 'src', check(el, mk) { if (mk !== 'interceptThirdParty') return false; const u = el.src; if (u && shouldBlockResource(u)) { LogManager.add(mk, el, { type: 'THIRD_PARTY', detail: `IFRAME: ${Utils.truncateString(u, 500)}` }); ResourceCanceller.cancelResourceLoading(el); ProcessedElementsCache.markAsProcessed(el); return true; } return false; } }, IMG: { srcAttr: 'src', dataSrcAttr: 'data-src', check(el, mk) { if (mk !== 'interceptThirdParty') return false; const u = el.src || el.getAttribute('data-src'); if (u && shouldBlockResource(u)) { LogManager.add(mk, el, { type: 'THIRD_PARTY', detail: `IMG: ${Utils.truncateString(u, 500)}` }); ResourceCanceller.cancelResourceLoading(el); ProcessedElementsCache.markAsProcessed(el); return true; } return false; } }, LINK: { srcAttr: 'href', check(el, mk) { if (mk !== 'interceptThirdParty') return false; const u = el.href; if (u && el.rel === 'stylesheet' && shouldBlockResource(u)) { LogManager.add(mk, el, { type: 'THIRD_PARTY', detail: `LINK: ${Utils.truncateString(u, 500)}` }); ResourceCanceller.cancelResourceLoading(el); ProcessedElementsCache.markAsProcessed(el); return true; } return false; } }, EMBED: { srcAttr: 'src', check(el, mk) { if (mk !== 'interceptThirdParty') return false; const u = el.src; if (u && shouldBlockResource(u)) { LogManager.add(mk, el, { type: 'THIRD_PARTY', detail: `EMBED: ${Utils.truncateString(u, 500)}` }); ResourceCanceller.cancelResourceLoading(el); ProcessedElementsCache.markAsProcessed(el); return true; } return false; } }, OBJECT: { srcAttr: 'data', check(el, mk) { if (mk !== 'interceptThirdParty') return false; const u = el.data; if (u && shouldBlockResource(u)) { LogManager.add(mk, el, { type: 'THIRD_PARTY', detail: `OBJECT: ${Utils.truncateString(u, 500)}` }); ResourceCanceller.cancelResourceLoading(el); ProcessedElementsCache.markAsProcessed(el); return true; } return false; } }, A: { srcAttr: 'href', check(el, mk) { if (mk !== 'interceptThirdParty') return false; const u = el.href; if (u && shouldBlockResource(u)) { LogManager.add(mk, el, { type: 'THIRD_PARTY', detail: `A: ${Utils.truncateString(u, 500)}` }); el.href = 'javascript:void(0)'; el.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); }, true); ProcessedElementsCache.markAsProcessed(el); return true; } return false; } } }; class BaseModule { constructor(mk) { this.moduleKey = mk; this.enabled = false; this.observer = null; } init() { currentConfig.modules[this.moduleKey] ? this.enable() : this.disable(); } enable() { if (this.enabled) return; this.enabled = true; this.onEnable(); } disable() { if (!this.enabled) return; this.enabled = false; this.onDisable(); } onEnable() { /* override in subclass */ } onDisable() { if (this.observer) { this.observer.disconnect(); this.observer = null; } } checkElement(el) { if (!Utils.shouldInterceptByModule(el, this.moduleKey)) return false; return this._checkElement(el); } _checkElement(el) { throw new Error('_checkElement must be implemented'); } } class RemoveInlineScriptsModule extends BaseModule { constructor() { super('removeInlineScripts'); this.attributeObserver = null; } onEnable() { _document.querySelectorAll('script:not([src])').forEach(s => this.checkElement(s)); if (currentConfig.inlineScriptStrictMode) _document.querySelectorAll('*').forEach(el => this.sanitizeInlineEventAttributes(el)); this.observer = new _MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) { if (n.nodeType === 1) { if (currentConfig.inlineScriptStrictMode) this.sanitizeInlineEventAttributes(n); if (n.tagName === 'SCRIPT' && !n.src) this.checkElement(n); } } }); this.observer.observe(_document.documentElement, { childList: true, subtree: true }); if (currentConfig.inlineScriptStrictMode) { this.attributeObserver = new _MutationObserver(ms => { for (const m of ms) { if (m.type !== 'attributes' || m.target.nodeType !== 1) continue; const an = m.attributeName; const t = m.target; if (an && an.toLowerCase().startsWith('on')) { const v = t.getAttribute(an); if (v && typeof v === 'string' && v.trim() !== '') { const r = { type: '内联事件', detail: `属性: ${an}="${v}"` }; if (!Whitelisting.isReasonWhitelisted(r)) { LogManager.add(this.moduleKey, t, r); t.removeAttribute(an); ProcessedElementsCache.markAsProcessed(t); } } } else if (['href', 'src', 'action', 'data', 'formaction'].includes(an)) { const v = t.getAttribute(an); if (v && typeof v === 'string' && v.trim().toLowerCase().startsWith('javascript:')) { const r = { type: 'javascript URL', detail: `${an}="${v}"` }; if (!Whitelisting.isReasonWhitelisted(r)) { LogManager.add(this.moduleKey, t, r); t.removeAttribute(an); ProcessedElementsCache.markAsProcessed(t); } } } } }); this.attributeObserver.observe(_document.documentElement, { attributes: true, subtree: true, attributeFilter: ['onclick', 'onload', 'onerror', 'onmouseover', 'onfocus', 'onblur', 'onsubmit', 'onchange', 'onkeydown', 'onkeyup', 'ontouchstart', 'ontouchend', 'ontouchmove', 'oncontextmenu', 'href', 'src', 'action', 'data', 'formaction'] }); } } onDisable() { super.onDisable(); if (this.attributeObserver) { this.attributeObserver.disconnect(); this.attributeObserver = null; } } _checkElement(el) { if (el.tagName === 'SCRIPT' && !el.src) return TAG_HANDLERS.SCRIPT.check(el, this.moduleKey, { type: '内嵌脚本移除', detail: `内容: ${Utils.truncateString(el.textContent, 500)}` }); return false; } sanitizeInlineEventAttributes(el) { if (!Utils.isElement(el) || ProcessedElementsCache.isProcessed(el)) return false; let mod = false; if (el.attributes) { for (let i = el.attributes.length - 1; i >= 0; i--) { const a = el.attributes[i]; if (a.name.toLowerCase().startsWith('on') && typeof a.value === 'string' && a.value.trim() !== '') { const r = { type: '内联事件', detail: `属性: ${a.name}="${a.value}"` }; if (!Whitelisting.isReasonWhitelisted(r)) { LogManager.add(this.moduleKey, el, r); el.removeAttribute(a.name); mod = true; } } } } ['href', 'src', 'action', 'data', 'formaction'].forEach(attr => { const v = el.getAttribute(attr); if (v && typeof v === 'string' && v.trim().toLowerCase().startsWith('javascript:')) { const r = { type: 'javascript URL', detail: `${attr}="${v}"` }; if (!Whitelisting.isReasonWhitelisted(r)) { LogManager.add(this.moduleKey, el, r); el.removeAttribute(attr); mod = true; } } }); if (mod) ProcessedElementsCache.markAsProcessed(el); return mod; } updateStrictMode() { if (this.enabled) { this.onDisable(); this.onEnable(); } } } class RemoveExternalScriptsModule extends BaseModule { constructor() { super('removeExternalScripts'); } onEnable() { _document.querySelectorAll('script[src]').forEach(s => this.checkElement(s)); this.observer = new _MutationObserver(ms => { for (const m of ms) { if (m.type === 'childList') for (const n of m.addedNodes) { if (n.nodeType === 1) { if (n.tagName === 'SCRIPT' && n.src) this.checkElement(n); if (n.querySelectorAll) n.querySelectorAll('script[src]').forEach(s => this.checkElement(s)); } } else if (m.type === 'attributes' && m.attributeName === 'src') { const el = m.target; if (el.tagName === 'SCRIPT' && el.src) this.checkElement(el); } } }); this.observer.observe(_document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'] }); } _checkElement(el) { if (el.tagName === 'SCRIPT' && el.src) return TAG_HANDLERS.SCRIPT.check(el, this.moduleKey, { type: '外联脚本移除', detail: `SRC: ${Utils.truncateString(el.src, 500)}` }); return false; } } class ScriptBlacklistModeModule extends BaseModule { constructor() { super('scriptBlacklistMode'); this.activeBlacklistSet = null; this.lastBlacklistHash = ''; } updateActiveBlacklistSet() { const h = `${Array.from(currentConfig.scriptBlacklist).sort().join('|')}|${currentConfig.builtinBlacklistEnabled}|${Array.from(currentConfig.removedBuiltinKeywords).sort().join('|')}`; if (h !== this.lastBlacklistHash) { this.lastBlacklistHash = h; this.activeBlacklistSet = Utils.getActiveBlacklistSet(); } } onEnable() { this.updateActiveBlacklistSet(); _document.querySelectorAll('script').forEach(s => this.checkElement(s)); this.observer = new _MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) { if (n.nodeType === 1 && n.tagName === 'SCRIPT') this.checkElement(n); } }); this.observer.observe(_document.documentElement, { childList: true, subtree: true }); } _checkElement(el) { if (el.tagName !== 'SCRIPT') return false; this.updateActiveBlacklistSet(); const bl = this.activeBlacklistSet; if (!bl || bl.size === 0) return false; let matched = false, mk = ''; for (const kw of bl) { if (!kw) continue; if (el.src && el.src.includes(kw)) { matched = true; mk = kw; break; } if (!el.src && el.textContent && el.textContent.includes(kw)) { matched = true; mk = kw; break; } } if (matched) { LogManager.add(this.moduleKey, el, { type: 'SCRIPT_BLACKLIST', detail: `命中关键词: ${mk} - ${el.src ? `SRC: ${Utils.truncateString(el.src, 500)}` : `内嵌: ${Utils.truncateString(el.textContent, 500)}`}` }); ResourceCanceller.cancelResourceLoading(el); ProcessedElementsCache.markAsProcessed(el); return true; } return false; } } class HTMLSanitizer { constructor(mk) { this.moduleKey = mk; } filterHTMLString(html) { if (typeof html !== 'string' || !html.includes('<')) return html; const qr = /<(?:script|link|img|iframe|embed|object|a|form|base)[^>]*(?:src|href|data|action)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi; let need = false; let m; while ((m = qr.exec(html)) !== null) { if (m[1] || m[2] || m[3]) { const u = m[1] || m[2] || m[3]; if (u && shouldBlockResource(u)) { need = true; break; } } } if (!need) return html; try { const doc = new _globals.DOMParser().parseFromString(html, 'text/html'); doc.querySelectorAll('script,link,img,iframe,embed,object,a,form,base').forEach(el => { const t = el.tagName.toLowerCase(); let a; if (['script', 'img', 'iframe', 'embed'].includes(t)) a = 'src'; else if (['link', 'a', 'base'].includes(t)) a = 'href'; else if (t === 'object') a = 'data'; else if (t === 'form') a = 'action'; if (!a) return; const u = el.getAttribute(a); if (!u) return; if (t === 'link') { const r = el.getAttribute('rel'); if (!r || !r.includes('stylesheet')) return; } if (shouldBlockResource(u)) { LogManager.add(this.moduleKey, null, { type: 'THIRD_PARTY_HTML_INJECTION', detail: `阻止: ${t.toUpperCase()} ${Utils.truncateString(u, 500)}` }); if (t === 'img') { el.setAttribute(a, 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'); el.removeAttribute('srcset'); el.removeAttribute('data-src'); } else if (t === 'a' || t === 'form') el.removeAttribute(a); else el.remove(); } }); return doc.body.innerHTML; } catch (e) { return html; } } } class NetworkInterceptor { constructor(mk) { this.moduleKey = mk; this.restoredFns = []; } setupNetworkInterception() { const self = this; try { const origFetch = _fetch; _globals.fetch = new _Proxy(_fetch, { apply(t, ta, a) { const u = typeof a[0] === 'string' ? a[0] : a[0]?.url; if (u && shouldBlockResource(u)) { LogManager.add(self.moduleKey, null, { type: 'THIRD_PARTY', detail: `FETCH: ${Utils.truncateString(u, 500)}` }); return Promise.reject(new Error('广告拦截器:拦截第三方请求')); } return Reflect.apply(t, ta, a); } }); this.restoredFns.push(() => { try { _globals.fetch = origFetch; } catch (e) { /* ignore */ } }); } catch (e) { /* ignore */ } try { const oo = _XMLHttpRequest.prototype.open; const os = _XMLHttpRequest.prototype.send; _XMLHttpRequest.prototype.open = new _Proxy(oo, { apply(t, ta, a) { if (a[1] && shouldBlockResource(a[1])) { LogManager.add(self.moduleKey, null, { type: 'THIRD_PARTY', detail: `XHR: ${Utils.truncateString(a[1], 500)}` }); ta._adblockBlocked = true; return; } ta._adblockBlocked = false; return Reflect.apply(t, ta, a); } }); _XMLHttpRequest.prototype.send = new _Proxy(os, { apply(t, ta, a) { if (ta._adblockBlocked) return; return Reflect.apply(t, ta, a); } }); this.restoredFns.push(() => { try { _XMLHttpRequest.prototype.open = oo; } catch (e) { /* ignore */ } try { _XMLHttpRequest.prototype.send = os; } catch (e) { /* ignore */ } }); } catch (e) { /* ignore */ } } stopInterception() { this.restoredFns.forEach(fn => { try { fn(); } catch (e) { /* ignore */ } }); this.restoredFns = []; } } class DOMPrototypeHooker { constructor(mk, hs) { this.moduleKey = mk; this.htmlSanitizer = hs; this.restoredFns = []; this.observer = null; } setupProxyInterception() { const self = this; const lc = (el, attr, url, tag) => { LogManager.add(this.moduleKey, el, { type: 'THIRD_PARTY', detail: `${tag}: ${Utils.truncateString(url, 500)}` }); ResourceCanceller.cancelResourceLoading(el); ProcessedElementsCache.markAsProcessed(el); }; try { const osa = _Element.prototype.setAttribute; _Element.prototype.setAttribute = new _Proxy(osa, { apply(t, ta, a) { const handler = TAG_HANDLERS[ta.tagName]; if (handler && shouldBlockResource(a[1])) { const attrName = a[0] && typeof a[0] === 'string' ? a[0].toLowerCase() : a[0]; if ((handler.srcAttr && handler.srcAttr === attrName) || (handler.dataSrcAttr && handler.dataSrcAttr === attrName)) { lc(ta, a[0], a[1], ta.tagName); return; } } return Reflect.apply(t, ta, a); } }); this.restoredFns.push(() => { try { _Element.prototype.setAttribute = osa; } catch (e) { /* ignore */ } }); } catch (e) { /* ignore */ } for (const tag in TAG_HANDLERS) { const proto = _globals[`HTML${tag}Element`]?.prototype; if (!proto) continue; const sa = TAG_HANDLERS[tag].srcAttr; try { const desc = Object.getOwnPropertyDescriptor(proto, sa); if (desc && desc.set && desc.configurable !== false) { const os = desc.set; proto[sa] = { set: new _Proxy(os, { apply(t, ta, a) { if (shouldBlockResource(a[0])) { lc(ta, sa, a[0], tag); return; } return Reflect.apply(t, ta, a); } }), get: desc.get, configurable: false, enumerable: true }; this.restoredFns.push(() => { try { Object.defineProperty(proto, sa, desc); } catch (e) { /* ignore */ } }); } } catch (e) { /* ignore */ } } } setupHTMLInterception() { const self = this; try { const ihd = Object.getOwnPropertyDescriptor(_Element.prototype, 'innerHTML'); if (ihd && ihd.set) { const os = ihd.set; Object.defineProperty(_Element.prototype, 'innerHTML', { set(v) { return os.call(this, self.htmlSanitizer.filterHTMLString(v)); }, get: ihd.get, configurable: false, enumerable: true }); this.restoredFns.push(() => { try { Object.defineProperty(_Element.prototype, 'innerHTML', ihd); } catch (e) { /* ignore */ } }); } } catch (e) { /* ignore */ } try { const oi = _Element.prototype.insertAdjacentHTML; _Element.prototype.insertAdjacentHTML = new _Proxy(oi, { apply(t, ta, a) { return Reflect.apply(t, ta, [a[0], self.htmlSanitizer.filterHTMLString(a[1])]); } }); this.restoredFns.push(() => { try { _Element.prototype.insertAdjacentHTML = oi; } catch (e) { /* ignore */ } }); } catch (e) { /* ignore */ } } setupStrictDOMInterception() { const self = this; const check = (el) => { if (!el || !Utils.isElement(el)) return false; const t = el.tagName; if (TAG_HANDLERS[t]) { const h = TAG_HANDLERS[t]; const u = el[h.srcAttr] || el.getAttribute(h.srcAttr) || (h.dataSrcAttr && el.getAttribute(h.dataSrcAttr)); if (u && shouldBlockResource(u)) { LogManager.add(self.moduleKey, el, { type: 'THIRD_PARTY', detail: `严格拦截: ${t}: ${Utils.truncateString(u, 500)}` }); ResourceCanceller.cancelResourceLoading(el); ProcessedElementsCache.markAsProcessed(el); return true; } } return false; }; try { const oa = _Node.prototype.appendChild; _Node.prototype.appendChild = new _Proxy(oa, { apply(t, ta, a) { if (a[0] && Utils.isElement(a[0])) { const r = Reflect.apply(t, ta, a); check(a[0]); return r; } return Reflect.apply(t, ta, a); } }); this.restoredFns.push(() => { try { _Node.prototype.appendChild = oa; } catch (e) { /* ignore */ } }); } catch (e) { /* ignore */ } try { const oi = _Node.prototype.insertBefore; _Node.prototype.insertBefore = new _Proxy(oi, { apply(t, ta, a) { if (a[0] && Utils.isElement(a[0])) { const r = Reflect.apply(t, ta, a); check(a[0]); return r; } return Reflect.apply(t, ta, a); } }); this.restoredFns.push(() => { try { _Node.prototype.insertBefore = oi; } catch (e) { /* ignore */ } }); } catch (e) { /* ignore */ } } patchAttachShadow() { const self = this; const proto = _Element.prototype; try { if (proto.attachShadow && !proto._adblockOriginalAttachShadow) { proto._adblockOriginalAttachShadow = proto.attachShadow; proto.attachShadow = function (init) { const shadow = proto._adblockOriginalAttachShadow.call(this, init); self.observeShadowRoot(shadow); const ihd = Object.getOwnPropertyDescriptor(shadow, 'innerHTML'); if (ihd && ihd.set && ihd.configurable) Object.defineProperty(shadow, 'innerHTML', { get: typeof ihd.get === 'function' ? function () { return ihd.get.call(this); } : undefined, set(v) { ihd.set.call(this, self.htmlSanitizer.filterHTMLString(v)); }, configurable: true }); return shadow; }; this.restoredFns.push(() => { if (proto._adblockOriginalAttachShadow) { proto.attachShadow = proto._adblockOriginalAttachShadow; delete proto._adblockOriginalAttachShadow; } }); } } catch (e) { /* ignore */ } } observeShadowRoot(sr) { if (!sr || sr._adblockObserved) return; sr._adblockObserved = true; const self = this; const obs = new _MutationObserver((ms) => { for (const m of ms) for (const n of m.addedNodes) { if (n.nodeType !== 1) continue; const t = n.tagName; if (TAG_HANDLERS[t]) { const h = TAG_HANDLERS[t]; const u = n[h.srcAttr] || n.getAttribute(h.srcAttr) || (h.dataSrcAttr && n.getAttribute(h.dataSrcAttr)); if (u && shouldBlockResource(u)) { LogManager.add(self.moduleKey, n, { type: 'THIRD_PARTY', detail: `Shadow DOM ${t}: ${Utils.truncateString(u, 500)}` }); ResourceCanceller.cancelResourceLoading(n); ProcessedElementsCache.markAsProcessed(n); } } if (n.shadowRoot) self.observeShadowRoot(n.shadowRoot); } }); obs.observe(sr, { childList: true, subtree: true }); this.restoredFns.push(() => { obs.disconnect(); delete sr._adblockObserved; }); } stopInterception() { this.restoredFns.forEach(fn => { try { fn(); } catch (e) { /* ignore */ } }); this.restoredFns = []; if (this.observer) { this.observer.disconnect(); this.observer = null; } } } class ThirdPartyInterceptionModule extends BaseModule { constructor() { super('interceptThirdParty'); this.htmlSanitizer = new HTMLSanitizer(this.moduleKey); this.networkInterceptor = new NetworkInterceptor(this.moduleKey); this.domHooker = new DOMPrototypeHooker(this.moduleKey, this.htmlSanitizer); } onEnable() { this.stopInterception(); this.domHooker.setupProxyInterception(); this.networkInterceptor.setupNetworkInterception(); this.setupMutationFallback(); this.domHooker.setupHTMLInterception(); this.domHooker.patchAttachShadow(); if (currentConfig.thirdPartyStrictMethod) this.domHooker.setupStrictDOMInterception(); } onDisable() { this.stopInterception(); } stopInterception() { this.networkInterceptor.stopInterception(); this.domHooker.stopInterception(); if (this.observer) { this.observer.disconnect(); this.observer = null; } } setupMutationFallback() { const self = this; this.observer = new _MutationObserver((ms) => { for (const m of ms) for (const n of m.addedNodes) { if (n.nodeType !== 1) continue; const t = n.tagName; if (TAG_HANDLERS[t]) { const h = TAG_HANDLERS[t]; const u = n[h.srcAttr] || n.getAttribute(h.srcAttr) || (h.dataSrcAttr && n.getAttribute(h.dataSrcAttr)); if (u && shouldBlockResource(u)) { LogManager.add(self.moduleKey, n, { type: 'THIRD_PARTY', detail: `${t}: ${Utils.truncateString(u, 500)}` }); ResourceCanceller.cancelResourceLoading(n); ProcessedElementsCache.markAsProcessed(n); } } if (n.shadowRoot) self.domHooker.observeShadowRoot(n.shadowRoot); } }); this.observer.observe(_document.documentElement, { childList: true, subtree: true }); } updateStrictMode() { urlCache.clear(); } updateStrictMethod() { if (this.enabled) { this.onDisable(); this.onEnable(); } } _checkElement(el) { const t = el.tagName; if (!TAG_HANDLERS[t]) return false; const h = TAG_HANDLERS[t]; const u = el[h.srcAttr] || el.getAttribute(h.srcAttr) || (h.dataSrcAttr && el.getAttribute(h.dataSrcAttr)); if (u && shouldBlockResource(u)) { LogManager.add(this.moduleKey, el, { type: 'THIRD_PARTY', detail: `${t}: ${Utils.truncateString(u, 500)}` }); ResourceCanceller.cancelResourceLoading(el); ProcessedElementsCache.markAsProcessed(el); return true; } return false; } } const CSPModule = { init() { if (currentConfig.modules.manageCSP) this.applyCSP(); }, applyCSP() { if (!currentConfig.modules.manageCSP) return; const ex = _document.querySelector('meta[http-equiv="Content-Security-Policy"]'); if (ex) ex.remove(); const er = currentConfig.cspRules.filter(r => r.enabled); if (er.length === 0) return; const dirs = {}; for (const r of er) { const p = r.rule.split(/\s+/); const d = p[0]; const v = p.slice(1); if (!dirs[d]) dirs[d] = new _Set(); v.forEach(x => dirs[d].add(x)); } let ps = ''; for (const d in dirs) { if (dirs.hasOwnProperty(d)) ps += `${d} ${Array.from(dirs[d]).join(' ')}; `; } ps = ps.trim(); if (!ps) return; const inject = () => { if (_document.head) { if (!_document.querySelector('meta[http-equiv="Content-Security-Policy"]')) { const m = _document.createElement('meta'); m.httpEquiv = "Content-Security-Policy"; m.content = ps; _document.head.appendChild(m); } } else { new _MutationObserver(() => { if (_document.head) { this.disconnect(); if (!_document.querySelector('meta[http-equiv="Content-Security-Policy"]')) { const m = _document.createElement('meta'); m.httpEquiv = "Content-Security-Policy"; m.content = ps; _document.head.appendChild(m); } } }).observe(_document.documentElement, { childList: true, subtree: true }); } }; inject(); }, updateRule(id, enabled) { const r = currentConfig.cspRules.find(x => x.id === id); if (r) r.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; touch-action: manipulation; } 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-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; margin-bottom: 8px; } .module-switch { display: flex; align-items: center; justify-content: space-between; padding: 6px 10px; background: #f8f9fa; border-radius: 10px; border: 1px solid #eee; } .switch-label { font-size: 13px; font-weight: 600; color: #333; display: flex; align-items: center; gap: 6px; } .info-icon { display: inline-flex; align-items: center; justify-content: center; width: 18px; height: 18px; background: #007AFF; color: white; border-radius: 50%; font-size: 12px; font-weight: bold; cursor: pointer; margin-left: 4px; } .info-icon:hover { background: #0056b3; } .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; touch-action: manipulation; } .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; } .panel::-webkit-scrollbar { width: 6px; } .panel::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 4px; } .panel::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 4px; } .log-entry.whitelisted { background-color: #e8f5e8; } .log-entry.keyword-whitelisted { background-color: #e0f0ff; } .log-entry.blacklisted { background-color: #ffe0e0; } .toast-container { position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%); z-index: ${CONFIG.Z_INDEX + 7}; pointer-events: none; display: flex; flex-direction: column; align-items: center; gap: 8px; } .toast { background: rgba(0, 0, 0, 0.85); color: #fff; padding: 12px 20px; border-radius: 10px; font-size: 14px; max-width: 85vw; text-align: center; line-height: 1.5; opacity: 0; transform: translateY(10px); animation: toast-in 0.3s ease forwards; white-space: pre-line; word-break: break-word; } .confirm-msg { text-align: center; font-size: 14px; color: #555; padding: 16px 8px; line-height: 1.6; white-space: pre-line; } @keyframes toast-in { to { opacity: 1; transform: translateY(0); } } @keyframes toast-out { to { opacity: 0; transform: translateY(10px); } } @media (orientation: landscape) and (max-height: 500px) { .btn-group button { flex: 1 0 100%; min-width: 80px; } .module-grid { grid-template-columns: repeat(3, 1fr); } .panel { max-height: 95vh; padding: 12px 10px; } .sub-panel { max-height: 50vh; } } @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; } .panel::-webkit-scrollbar-track { background: #2c2c2e; } .panel::-webkit-scrollbar-thumb { background: #555; } .log-entry.whitelisted { background-color: #2a4a2a; } .log-entry.keyword-whitelisted { background-color: #2a3a5a; } .log-entry.blacklisted { background-color: #5a2a2a; } .toast { background: rgba(255, 255, 255, 0.9); color: #1c1c1e; } .confirm-msg { color: #ddd; } } @keyframes fade-in { to { background: rgba(0, 0, 0, 0.3); backdrop-filter: blur(8px); } } @keyframes scale-in { to { transform: scale(1); opacity: 1; } } `; let panelIdCounter = 0; class PanelManager { constructor() { this.shadowRoot = null; this.settingsContainer = null; this.toastContainer = null; this.isAnimating = false; this.currentController = null; } ensureShadow() { if (this.shadowRoot) return; this.settingsContainer = _document.createElement('div'); this.settingsContainer.id = 'ad-blocker-settings-container'; this.settingsContainer.style.cssText = `position:fixed;top:0;left:0;width:100%;height:100%;z-index:${CONFIG.Z_INDEX + 7};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); this.toastContainer = _document.createElement('div'); this.toastContainer.className = 'toast-container'; this.shadowRoot.appendChild(this.toastContainer); ProcessedElementsCache.markAsProcessed(this.settingsContainer); } showToast(message, duration = 3500) { this.ensureShadow(); if (!this.shadowRoot || !this.toastContainer) return; const t = _document.createElement('div'); t.className = 'toast'; t.textContent = message; this.toastContainer.appendChild(t); _setTimeout(() => { t.style.animation = 'toast-out 0.3s ease forwards'; _setTimeout(() => { if (t.parentNode) t.parentNode.removeChild(t); }, 300); }, duration); } showConfirm(message, onConfirm) { const panelManager = this; this.createPanel({ title: '⚠️ 操作确认', contentHtml: `
${escapeHtml(message)}
`, buttons: [ { id: 'confirmOk', text: '确认执行', class: 'danger', onclick: () => { panelManager.closeCurrentMask(); if (onConfirm) onConfirm(); } }, { id: 'confirmNo', text: '取消', onclick: (e, m) => { if (m && m._closePanel) m._closePanel(); } } ], hideBackButton: true, onBack: () => { /* 点击遮罩层 = 取消 */ } }); } closeCurrentMask() { const m = this.shadowRoot?.querySelector('.mask'); if (!m) return; if (this.currentController) { this.currentController.abort(); this.currentController = null; } const pid = m.getAttribute('data-panel-id'); if (pid) teardownNavigationBlocking(pid); m.style.transition = 'none'; m.remove(); this.isAnimating = false; } createPanel(options) { if (this.isAnimating) return null; const { title, contentHtml, onClose, onBack, buttons = [], hideBackButton = false, isRootPanel = false } = options; this.ensureShadow(); this.closeCurrentMask(); const panelId = `panel_${++panelIdCounter}`; setupNavigationBlocking(panelId); const controller = _AbortController ? new _AbortController() : null; const signal = controller ? controller.signal : undefined; this.currentController = controller; const mask = _document.createElement('div'); mask.className = 'mask'; mask.setAttribute('data-adblock-safe', 'true'); mask.setAttribute('data-panel-id', panelId); const btnHtml = buttons.map(b => ``).join(''); const backHtml = hideBackButton ? '' : ``; mask.innerHTML = `
${escapeHtml(title)}
${contentHtml}
${btnHtml}${backHtml}
`; const closePanel = (anim = true) => { if (!mask.parentNode) return; teardownNavigationBlocking(panelId); const doRemove = () => { if (controller) controller.abort(); mask.remove(); this.isAnimating = false; if (this.currentController === controller) this.currentController = null; if (onClose) onClose(); }; if (anim) { this.isAnimating = true; const onTE = () => { mask.removeEventListener('transitionend', onTE); doRemove(); }; mask.addEventListener('transitionend', onTE); mask.style.opacity = '0'; _setTimeout(() => { if (mask.parentNode) { mask.removeEventListener('transitionend', onTE); doRemove(); } }, 500); } else doRemove(); }; mask._closePanel = closePanel; const handleBack = () => { if (isRootPanel) return; closePanel(); if (onBack) onBack(); else this.showSettings(); }; mask.addEventListener('click', (e) => { const path = e.composedPath(); const isPanel = path.some(el => Utils.isPanelElement(el)); if (!isPanel && e.target === mask) { handleBack(); return; } if (isPanel) { if (!e.target.closest('button, input, textarea, select, label, .info-icon, .whitelist-btn')) { handleBack(); return; } } const button = e.target.closest('button'); if (!button) return; const action = button.dataset.action || button.dataset.id; if (action === 'backBtn') { handleBack(); return; } const matched = buttons.find(b => b.id === action); if (matched && matched.onclick) { matched.onclick(e, mask); return; } this.handlePanelAction(action, button.dataset.index, button, mask, e); }, { signal }); mask.addEventListener('change', (e) => { const t = e.target; if (t.matches('.module-toggle')) { const k = t.dataset.key; currentConfig.modules[k] = t.checked; ConfigUpdater.saveNow(); resetAllCachesAndStates(); if (k === 'removeInlineScripts' && inlineScriptsModule) inlineScriptsModule.init(); if (k === 'interceptThirdParty' && thirdPartyModule) thirdPartyModule.init(); if (strongBlockingEnabled) disableStrongBlocking(); const any = Object.values(currentConfig.modules).some(v => v === true); if (currentConfig.residualCleanupEnabled && any) ResidualCleaner.init(); else ResidualCleaner.stop(); } else if (t.matches('.csp-toggle')) { CSPModule.updateRule(parseInt(t.dataset.id), t.checked); currentConfig.modules.manageCSP = currentConfig.cspRules.some(r => r.enabled); ConfigUpdater.saveNow(); _location.reload(); } else if (t.matches('.advanced-toggle')) { const k = t.dataset.key; currentConfig[k] = t.checked; ConfigUpdater.saveNow(); if (k === 'inlineScriptStrictMode' && inlineScriptsModule) inlineScriptsModule.updateStrictMode(); if (k === 'thirdPartyStrictMode' && thirdPartyModule) thirdPartyModule.updateStrictMode(); if (k === 'thirdPartyStrictMethod' && thirdPartyModule) thirdPartyModule.updateStrictMethod(); if (k === 'residualCleanupEnabled') { const any = Object.values(currentConfig.modules).some(v => v === true); if (currentConfig.residualCleanupEnabled && any) ResidualCleaner.init(); else ResidualCleaner.stop(); } if (k === 'cssUniversalHideEnabled') CSSUniversalHider.init(); if (k === 'builtinBlacklistEnabled' && t.checked) currentConfig.removedBuiltinKeywords.clear(); } }, { signal }); this.shadowRoot.appendChild(mask); mask.style.pointerEvents = 'auto'; mask.querySelector('.panel').style.pointerEvents = 'auto'; return mask; } renderLogItem(log, index) { const status = getLogWhitelistStatus(log); const logEntryClass = 'log-entry' + (status ? ` ${status}` : ''); const isWL = status !== ''; const domainHint = log.domain ? `
域名: ${escapeHtml(log.domain)}
` : ''; return `
${escapeHtml(log.module)} - ${escapeHtml(log.element)}
${escapeHtml(log.content)}
${domainHint}
`; } handlePanelAction(action, index, button, mask, event) { switch (action) { case 'deleteDiaryItem': { const arr = Array.from(currentConfig.whitelist); const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < arr.length && arr[idx]) { currentConfig.whitelist.delete(arr[idx]); ConfigUpdater.saveNow(); resetAllCachesAndStates(); this.showDiaryWhitelistPanel(); } break; } case 'deleteKeywordItem': { const arr = Array.from(currentConfig.keywordWhitelist); const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < arr.length && arr[idx]) { currentConfig.keywordWhitelist.delete(arr[idx]); ConfigUpdater.saveNow(); resetAllCachesAndStates(); this.showKeywordWhitelistPanel(); } break; } case 'deleteBlacklistItem': { const arr = Utils.getActiveBlacklistArray(); const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < arr.length && arr[idx]) { if (BUILTIN_BLACKLIST_KEYWORDS.includes(arr[idx])) currentConfig.removedBuiltinKeywords.add(arr[idx]); else currentConfig.scriptBlacklist.delete(arr[idx]); ConfigUpdater.saveNow(); resetAllCachesAndStates(); this.showScriptBlacklistPanel(); } break; } case 'deleteThirdPartyItem': { const wl = currentConfig.thirdPartyWhitelist; const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < wl.length && wl[idx]) { const removedItem = wl[idx]; wl.splice(idx, 1); if (removedItem) Whitelisting.removeKeywordsMatchingDomain(removedItem); ConfigUpdater.saveNow(); resetAllCachesAndStates(); this.showThirdPartyPanel(); } break; } case 'whitelistLog': { const logs = LogManager.logs; const idx = parseInt(index); if (!isNaN(idx) && idx >= 0 && idx < logs.length && logs[idx]?.contentIdentifier) { const le = logs[idx]; const isTPD = currentConfig.modules.interceptThirdParty && le.domain; if (isTPD && le.domain) { if (!currentConfig.thirdPartyWhitelist.includes(le.domain)) currentConfig.thirdPartyWhitelist.push(le.domain); logs.forEach(e => { if (e.domain === le.domain && !currentConfig.thirdPartyWhitelist.includes(e.domain)) currentConfig.thirdPartyWhitelist.push(e.domain); }); ConfigUpdater.saveNow(); mask.querySelectorAll('.log-entry').forEach(div => { const btn = div.querySelector('.whitelist-btn'); if (!btn) return; const bi = parseInt(btn.dataset.index); if (!isNaN(bi) && logs[bi]?.domain === le.domain) { div.classList.add('whitelisted'); btn.disabled = true; btn.textContent = '已加白'; btn.style.backgroundColor = '#999'; } }); } else { if (!currentConfig.whitelist.has(le.contentIdentifier)) currentConfig.whitelist.add(le.contentIdentifier); ConfigUpdater.saveNow(); const ld = button.closest('.log-entry'); if (ld) { ld.classList.add('whitelisted'); button.disabled = true; button.textContent = '已加白'; button.style.backgroundColor = '#999'; } } resetAllCachesAndStates(); } break; } case 'addToBlacklist': { const enc = button.dataset.content; if (enc) { currentConfig.scriptBlacklist.add(decodeURIComponent(enc)); ConfigUpdater.saveNow(); const ld = button.closest('.log-entry'); if (ld) { const tb = ld.querySelector('button[data-action="addToBlacklist"]'); if (tb) { tb.disabled = true; tb.textContent = '已加黑'; tb.style.backgroundColor = '#999'; } ld.classList.add('blacklisted'); } } break; } case 'addKeywordWhitelist': { const inp = mask.querySelector('#keywordWhitelistInput'); const kw = inp.value.trim(); if (kw) { Whitelisting.addKeyword(kw); inp.value = ''; this.showLogsPanel(); } break; } case 'addWhitelist': { const inp = mask.querySelector('#newWhitelist'); let v = inp.value.trim(); if (v) { v = v.replace(/^https?:\/\//, ''); try { v = new URL('http://' + v).hostname; } catch (e) { /* ignore */ } if (!currentConfig.thirdPartyWhitelist.includes(v)) currentConfig.thirdPartyWhitelist.push(v); ConfigUpdater.saveNow(); inp.value = ''; resetAllCachesAndStates(); this.showThirdPartyPanel(); } break; } case 'addBlacklist': { const inp = mask.querySelector('#newBlacklistKeyword'); const kw = inp.value.trim(); if (kw) { currentConfig.scriptBlacklist.add(kw); ConfigUpdater.saveNow(); inp.value = ''; resetAllCachesAndStates(); this.showScriptBlacklistPanel(); } break; } case 'addBlacklistFromDomain': { const d = decodeURIComponent(button.dataset.domain); if (d) { currentConfig.scriptBlacklist.add(d); ConfigUpdater.saveNow(); const ld = button.closest('.log-entry'); if (ld) { const tb = ld.querySelector('button[data-action="addBlacklistFromDomain"]'); if (tb) { tb.disabled = true; tb.textContent = '域名已加黑'; tb.style.backgroundColor = '#999'; } ld.classList.add('blacklisted'); } } break; } case 'clearAllDiary': { this.showConfirm('确定清空所有日记白名单吗?', () => { currentConfig.whitelist.clear(); ConfigUpdater.saveNow(); resetAllCachesAndStates(); this.showDiaryWhitelistPanel(); }); break; } case 'clearAllKeyword': { this.showConfirm('确定清空所有关键词白名单吗?', () => { currentConfig.keywordWhitelist.clear(); ConfigUpdater.saveNow(); resetAllCachesAndStates(); this.showKeywordWhitelistPanel(); }); break; } case 'clearAllBlacklist': { this.showConfirm('确定清空所有脚本黑名单吗?', () => { currentConfig.scriptBlacklist.clear(); currentConfig.removedBuiltinKeywords.clear(); ConfigUpdater.saveNow(); resetAllCachesAndStates(); this.showScriptBlacklistPanel(); }); break; } case 'clearAllThirdParty': { this.showConfirm('确定清空所有第三方白名单吗?', () => { currentConfig.thirdPartyWhitelist = []; ConfigUpdater.saveNow(); resetAllCachesAndStates(); this.showThirdPartyPanel(); }); break; } case 'showScriptList': { this.showScriptListPanel(); break; } case 'enableCSP': { currentConfig.modules.manageCSP = true; ConfigUpdater.saveNow(); _location.reload(); break; } case 'disableCSP': { currentConfig.modules.manageCSP = false; ConfigUpdater.saveNow(); _location.reload(); break; } case 'allOn': { currentConfig.cspRules.forEach(r => r.enabled = true); currentConfig.modules.manageCSP = true; ConfigUpdater.saveNow(); _location.reload(); break; } case 'allOff': { currentConfig.cspRules.forEach(r => r.enabled = false); currentConfig.modules.manageCSP = false; ConfigUpdater.saveNow(); _location.reload(); break; } case 'closePanel': { if (mask._closePanel) mask._closePanel(); break; } case 'showAdvancedSettings': { this.showAdvancedSettingsPanel(); break; } case 'loadMoreLogs': { this.loadMoreLogs(mask); break; } case 'loadMoreScripts': { this.loadMoreScripts(mask); break; } } } showAdvancedSettingsPanel() { this.closeCurrentMask(); const infoMap = { redirectBlocker: '启用后,尝试拦截所有跳转到第三方、非同源域名的行为。\n\n若关闭"拦截第三方资源-严格模式",则允许同主域的子域名跳转。使用正确的公共后缀列表进行域名判断。', inlineStrict: '严格模式:额外拦截内联事件(如onclick)和javascript:URL,适用于拦截点击弹窗、悬浮广告等。\n宽松模式(默认):仅移除内嵌脚本内容。', thirdPartyStrict: '严格模式:拦截所有第三方资源(包括子域名和兄弟域名)。\n宽松模式(默认):只拦截完全无关的第三方域名(主域名不同)。\n\n此选项同时影响"同源跳转拦截"的行为。使用正确的公共后缀列表进行域名判断。', thirdPartyMethod: '严格劫持方式:在宽松模式基础上,额外劫持 appendChild 方法,拦截动态创建的第三方资源。可能影响性能,建议仅在必要时开启。', residualCleanup: '清空残留容器:在浏览器空闲时清理有明显广告样式且内容为空的容器,忽略尺寸很小的元素。', cssUniversalHide: 'CSS通用隐藏:动态检测高z-index(>600)特征的广告元素并隐藏。可能误伤正常元素,建议仅在必要时开启。', iframeUIFix: '当在某些视频网站打开设置面板时,如果视频播放器和网页都弹出了控制面板,开启此选项可能修复该问题。', builtinBlacklist: '启用后,脚本黑名单模式将使用内置的广告特征关键词列表进行拦截。关闭则不使用内置列表,仅使用您手动添加的黑名单。重新开启会恢复所有内置关键词。' }; const c = currentConfig; this.createPanel({ title: '高级设置中心', contentHtml: `
同源跳转拦截 !
清空残留容器 !
CSS通用隐藏 !
内置黑名单 !
移除内嵌脚本-严格模式 !
拦截第三方-严格模式 !
拦截第三方-严格劫持方式 !
禁止在嵌套框架中显示面板 !
`, buttons: [], onBack: () => this.showSettings() }); const me = this.shadowRoot.querySelector('.mask:last-child'); if (me) me.querySelectorAll('.info-icon').forEach(icon => { icon.addEventListener('click', (e) => { e.stopPropagation(); this.showToast(infoMap[icon.dataset.info] || '点击查看详情', 5000); }); }); } showSettings() { this.closeCurrentMask(); const ms = Object.keys(MODULE_NAMES).map(k => `
${escapeHtml(MODULE_NAMES[k])}
`).join(''); this.createPanel({ title: '🛡️广告拦截设置', contentHtml: `
功能模块:
${ms}
`, buttons: [ { id: 'viewLogs', text: `拦截日志 (${LogManager.logs.length})`, onclick: () => this.showLogsPanel() }, { id: 'manageCSP', text: 'CSP策略管理', onclick: () => this.showCSPPanel() }, { id: 'manageDiaryWhitelist', text: '日记白名单', onclick: () => this.showDiaryWhitelistPanel() }, { id: 'manageThirdParty', text: '第三方白名单', onclick: () => this.showThirdPartyPanel() }, { id: 'manageKeywordWhitelist', text: '关键词白名单', onclick: () => this.showKeywordWhitelistPanel() }, { id: 'manageScriptBlacklist', text: '脚本黑名单', onclick: () => this.showScriptBlacklistPanel() }, { id: 'showAdvancedSettings', text: '高级设置中心', onclick: () => this.showAdvancedSettingsPanel() }, { id: 'closePanel', text: '返回网页', onclick: (e, m) => { if (m._closePanel) m._closePanel(); } } ], hideBackButton: true, isRootPanel: true }); } showDiaryWhitelistPanel() { this.closeCurrentMask(); const wl = Array.from(currentConfig.whitelist); const prefixMap = { 'INLINE_EVENT: ': '内联事件: ', 'JAVASCRIPT_URL: ': 'JS URL: ', 'SCRIPT_CONTENT: ': '脚本内容: ', 'SCRIPT_SRC: ': '脚本SRC: ', 'EVAL_HASH: ': 'Eval哈希: ', 'FUNCTION_HASH: ': 'Function哈希: ', 'DOCUMENT_WRITE_HASH: ': 'document.write哈希: ', 'SETTIMEOUT_HASH: ': 'setTimeout哈希: ', 'SETINTERVAL_HASH: ': 'setInterval哈希: ', 'REQUESTANIMATIONFRAME_HASH: ': 'RAF哈希: ' }; const html = wl.length > 0 ? wl.map((item, i) => { let display = item; for (const [prefix, label] of Object.entries(prefixMap)) { if (item.startsWith(prefix)) { display = label + item.substring(prefix.length); break; } } return `
${escapeHtml(display)}
`; }).join('') : '
日记白名单为空
'; this.createPanel({ title: `日记白名单 (${wl.length}项)`, contentHtml: `
查看和管理拦截日记中添加的白名单条目
${html}
`, buttons: [], onBack: () => this.showSettings() }); } showKeywordWhitelistPanel() { this.closeCurrentMask(); const kws = Array.from(currentConfig.keywordWhitelist); const html = kws.length > 0 ? kws.map((kw, i) => `
${escapeHtml(kw)}
`).join('') : '
关键词白名单为空
'; this.createPanel({ title: `关键词白名单 (${kws.length}项)`, contentHtml: `
查看和管理通过关键词添加的白名单条目
${html}
`, buttons: [], onBack: () => this.showSettings() }); } showScriptBlacklistPanel() { this.closeCurrentMask(); const bl = Utils.getActiveBlacklistArray(); const html = bl.length > 0 ? bl.map((kw, i) => `
${escapeHtml(kw)}
`).join('') : '
脚本黑名单为空
'; this.createPanel({ title: `脚本黑名单 (${bl.length}项)`, contentHtml: `
脚本黑名单模式将拦截内嵌/外联脚本中匹配这些关键词的资源
${html}
`, buttons: [], onBack: () => this.showSettings() }); _setTimeout(() => { const me = this.shadowRoot?.querySelector('.mask:last-child'); if (!me) return; const inp = me.querySelector('#newBlacklistKeyword'); if (inp) { inp.focus(); inp.addEventListener('keypress', (e) => { if (e.key === 'Enter') { const b = me.querySelector('[data-id="addBlacklist"]'); if (b) b.click(); } }); } }, 0); } showScriptListPanel() { this.closeCurrentMask(); const scripts = Array.from(_document.scripts); const items = scripts.map((s, i) => { const isExternal = !!s.src; return { index: i + 1, isExternal: isExternal, content: Utils.truncateString(isExternal ? s.src : s.textContent, 500), script: s }; }); const bls = Utils.getActiveBlacklistSet(); const PS = 20; const initial = items.slice(0, PS); const renderItem = (item) => { const sContent = item.isExternal ? item.script.src : item.script.textContent; const isBL = bls.has(sContent); let domainHint = '', extractBtn = '', isDBL = false; if (item.isExternal && item.script.src) { try { const d = new URL(item.script.src, _location.href).hostname; if (d) { domainHint = `
域名: ${escapeHtml(d)}
`; isDBL = bls.has(d); extractBtn = ``; } } catch (e) { /* ignore */ } } const cls = 'log-entry' + ((isBL || isDBL) ? ' blacklisted' : ''); return `
脚本 #${item.index} - ${item.isExternal ? '外联' : '内嵌'}
${escapeHtml(item.content)}
${domainHint}${extractBtn}
`; }; this.createPanel({ title: `当前网页脚本列表 (共${scripts.length}个)`, contentHtml: `
点击「加黑」将整个脚本内容添加到脚本黑名单;「加黑域名」将脚本域名加入黑名单
${initial.map(renderItem).join('')}
${items.length > PS ? `` : ''}`, buttons: [], onBack: () => this.showScriptBlacklistPanel() }); } loadMoreScripts(mask) { const scripts = Array.from(_document.scripts); const bls = Utils.getActiveBlacklistSet(); const PS = 20; const container = mask.querySelector('[data-panel="scriptList"]'); const btn = mask.querySelector('[data-id="loadMoreScripts"]'); const cur = container.children.length; if (cur >= scripts.length) { if (btn) btn.remove(); return; } const batch = scripts.slice(cur, cur + PS); const frag = _document.createDocumentFragment(); const tmp = _document.createElement('div'); batch.forEach((s, idx) => { const ri = cur + idx + 1; const isExt = !!s.src; const content = Utils.truncateString(isExt ? s.src : s.textContent, 500); const sContent = isExt ? s.src : s.textContent; const isBL = bls.has(sContent); let domainHint = '', extractBtn = '', isDBL = false; if (isExt && s.src) { try { const d = new URL(s.src, _location.href).hostname; if (d) { domainHint = `
域名: ${escapeHtml(d)}
`; isDBL = bls.has(d); extractBtn = ``; } } catch (e) { /* ignore */ } } const cls = 'log-entry' + ((isBL || isDBL) ? ' blacklisted' : ''); tmp.innerHTML = `
脚本 #${ri} - ${isExt ? '外联' : '内嵌'}
${escapeHtml(content)}
${domainHint}${extractBtn}
`; while (tmp.firstChild) frag.appendChild(tmp.firstChild); }); container.appendChild(frag); const nc = container.children.length; if (nc >= scripts.length) { if (btn) btn.remove(); } else if (btn) btn.textContent = `加载更多 (${nc}/${scripts.length})`; } showLogsPanel() { this.closeCurrentMask(); const logs = LogManager.logs; const PS = 20; const initial = logs.slice(0, PS); this.createPanel({ title: `拦截日志 (${logs.length}条)`, contentHtml: `
关键词加白(添加包含关键词的脚本到白名单):
${initial.map((l, i) => this.renderLogItem(l, i)).join('')}
${logs.length > PS ? `` : ''}`, buttons: [], onBack: () => this.showSettings() }); _setTimeout(() => { const me = this.shadowRoot?.querySelector('.mask:last-child'); if (!me) return; const inp = me.querySelector('#keywordWhitelistInput'); if (inp) { inp.focus(); inp.addEventListener('keypress', (e) => { if (e.key === 'Enter') { const b = me.querySelector('[data-id="addKeywordWhitelist"]'); if (b) b.click(); } }); } }, 0); } loadMoreLogs(mask) { const logs = LogManager.logs; const PS = 20; const container = mask.querySelector('[data-panel="logList"]'); const btn = mask.querySelector('[data-id="loadMoreLogs"]'); const cur = container.children.length; if (cur >= logs.length) { if (btn) btn.remove(); return; } const batch = logs.slice(cur, cur + PS); const frag = _document.createDocumentFragment(); const tmp = _document.createElement('div'); batch.forEach((l, i) => { tmp.innerHTML = this.renderLogItem(l, cur + i); while (tmp.firstChild) frag.appendChild(tmp.firstChild); }); container.appendChild(frag); const nc = container.children.length; if (nc >= logs.length) { if (btn) btn.remove(); } else if (btn) btn.textContent = `加载更多 (${nc}/${logs.length})`; } showCSPPanel() { this.closeCurrentMask(); const rulesHtml = currentConfig.cspRules.map(r => `
${escapeHtml(r.name)}
`).join(''); this.createPanel({ title: 'CSP策略管理', contentHtml: `
当前状态: ${currentConfig.modules.manageCSP ? '✅已启用' : '❌已禁用'}
${rulesHtml}
`, buttons: [], onBack: () => this.showSettings() }); } showThirdPartyPanel() { this.closeCurrentMask(); const wl = currentConfig.thirdPartyWhitelist; const html = wl.length > 0 ? wl.map((item, i) => `
${escapeHtml(item)}
`).join('') : '
白名单为空
'; this.createPanel({ title: `第三方白名单 (${wl.length}项)`, contentHtml: `
已拦截的第三方域名可以添加到白名单中
${html}
`, buttons: [], onBack: () => this.showSettings() }); _setTimeout(() => { const me = this.shadowRoot?.querySelector('.mask:last-child'); if (!me) return; const inp = me.querySelector('#newWhitelist'); if (inp) { inp.focus(); inp.addEventListener('keypress', (e) => { if (e.key === 'Enter') { const b = me.querySelector('[data-id="addWhitelist"]'); if (b) b.click(); } }); } }, 0); } } class CentralScheduler { constructor(modules) { this.modules = modules; this.elementCheckCache = new WeakSet(); this.urlCheckCache = new LRUCache(500, CONFIG.CACHE_TTL); } shouldProcessElement(el) { return Utils.isElement(el) && !this.elementCheckCache.has(el) && !ProcessedElementsCache.isProcessed(el) && !Utils.isParentProcessed(el) && el.getAttribute('data-adblock-safe') !== 'true'; } processElement(el) { if (!this.shouldProcessElement(el)) return false; this.elementCheckCache.add(el); for (const m of this.modules) { if (m.enabled && m.checkElement(el)) { ProcessedElementsCache.markAsProcessed(el); return true; } } return false; } clearCache() { this.elementCheckCache = new WeakSet(); this.urlCheckCache.clear(); urlCache.clear(); } } let inlineScriptsModule = null; let thirdPartyModule = null; let centralScheduler = null; const UIController = { initialized: false, mutationObserver: null, batchProcessingQueue: [], batchSize: CONFIG.BATCH_SIZE, isProcessingBatch: false, lastProcessTime: 0, emaFrameTime: 16, 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(); const any = Object.values(currentConfig.modules).some(v => v === true); if (currentConfig.residualCleanupEnabled && any) ResidualCleaner.init(); else ResidualCleaner.stop(); CSSUniversalHider.init(); }, applyInitialModuleStates() { Object.keys(DEFAULT_MODULE_STATE).forEach(k => { if (currentConfig.modules[k] === undefined) currentConfig.modules[k] = DEFAULT_MODULE_STATE[k]; }); }, registerMenuCommands() { GM_registerMenuCommand('⚙️ 广告拦截设置面板', () => this.panelManager.showSettings()); GM_registerMenuCommand(`🍎 模拟UA ${currentConfig.spoofUAEnabled ? '✅ 已启用' : '❌ 已禁用'}`, () => { currentConfig.spoofUAEnabled = !currentConfig.spoofUAEnabled; ConfigUpdater.saveNow(); GM_notification({ text: `UA模拟已${currentConfig.spoofUAEnabled ? '启用' : '禁用'},刷新页面生效`, title: '广告拦截器' }); _location.reload(); }); GM_registerMenuCommand('🔄 当前域名重置所有设置', () => { this.panelManager.showConfirm('确定重置当前域名的所有设置吗?\n\n这将清空当前域名的所有白名单并关闭所有模块,恢复到初始状态。', () => { StorageManager.resetAllSettings(); resetAllCachesAndStates(); GM_notification({ text: '当前域名设置已重置', title: '广告拦截器' }); _location.reload(); }); }); GM_registerMenuCommand('⚠️ 全局重置所有设置', () => { this.panelManager.showConfirm('警告:此操作将清除所有域名的广告拦截配置!\n\n确定要全局重置吗?', () => { try { for (const k of GM_listValues()) { if (k.startsWith('adblock_unified_config_')) GM_deleteValue(k); } } catch (e) { /* ignore */ } GM_notification({ text: '全局设置已重置,正在刷新页面...', title: '广告拦截器' }); _location.reload(); }); }); GM_registerMenuCommand('🗑️ 清空所有白名单', () => { this.panelManager.showConfirm('确定清空当前域名的所有白名单(包括日记白名单、第三方白名单、关键词白名单等)吗?', () => { Whitelisting.clearAllWhitelists(); resetAllCachesAndStates(); GM_notification({ text: '所有白名单已清空', title: '广告拦截器' }); _location.reload(); }); }); }, createModules() { inlineScriptsModule = new RemoveInlineScriptsModule(); thirdPartyModule = new ThirdPartyInterceptionModule(); this.modules = [inlineScriptsModule, new RemoveExternalScriptsModule(), new ScriptBlacklistModeModule(), thirdPartyModule]; }, applyModuleSettings() { this.modules.forEach(m => m.init()); DynamicScriptInterceptor.init(); CSPModule.init(); centralScheduler = new CentralScheduler(this.modules); }, setupObservers() { if (!this.modules.some(m => m.enabled) || !currentConfig.modules.blockDynamicScripts) return; this.mutationObserver = new _MutationObserver(Utils.throttle((ms) => { for (const m of ms) for (const n of m.addedNodes) { if (n.nodeType === 1 && !ProcessedElementsCache.isProcessed(n) && !Utils.isParentProcessed(n)) this.addToBatchProcessingQueue(n); } }, 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() { try { _document.querySelectorAll('script[src], iframe[src], img[src], img[data-src], embed[src], object[data], link[href]').forEach(el => { if (ProcessedElementsCache.isProcessed(el) || Utils.isParentProcessed(el)) return; const t = el.tagName; let u; if (t === 'SCRIPT') u = el.src; else if (t === 'IFRAME') u = el.src; else if (t === 'IMG') u = el.src || el.getAttribute('data-src'); else if (t === 'EMBED') u = el.src; else if (t === 'OBJECT') u = el.data; else if (t === 'LINK') u = el.href; if (u && shouldBlockResource(u)) { const ci = Utils.getContentIdentifier(el); if (ci && !currentConfig.whitelist.has(ci)) LogManager.add('interceptThirdParty', el, { type: 'THIRD_PARTY_SCAN', detail: `扫描发现: ${t}: ${Utils.truncateString(u, 500)}` }); } }); } catch (e) { /* ignore */ } }, addToBatchProcessingQueue(el) { if (el.getAttribute?.('data-adblock-safe') === 'true') { ProcessedElementsCache.markAsProcessed(el); return; } this.batchProcessingQueue.push(el); if (!this.isProcessingBatch) this.processBatch(); }, processBatch() { if (!centralScheduler) return; this.isProcessingBatch = true; let bs = this.batchSize; const alpha = 0.2; const chunk = () => { const now = performance.now(); if (this.lastProcessTime > 0) { this.emaFrameTime = alpha * (now - this.lastProcessTime) + (1 - alpha) * this.emaFrameTime; bs = this.emaFrameTime > 16 ? Math.max(5, Math.round(bs * 0.9)) : Math.min(50, Math.round(bs * 1.1)); } this.lastProcessTime = now; const batch = this.batchProcessingQueue.splice(0, bs); batch.forEach(n => centralScheduler.processElement(n)); if (this.batchProcessingQueue.length > 0) _requestAnimationFrame(chunk); else this.isProcessingBatch = false; }; _requestAnimationFrame(chunk); }, processExistingElementsBatch() { const els = Array.from(_document.querySelectorAll('script, iframe, img, a[href], style, link[rel="preload"], link[rel="prefetch"], embed, object, link[href]')); const process = () => { const batch = els.splice(0, this.batchSize * 2); batch.forEach(el => { if (!ProcessedElementsCache.isProcessed(el) && !Utils.isParentProcessed(el)) this.addToBatchProcessingQueue(el); }); if (els.length > 0) _requestIdleCallback(process); }; _requestIdleCallback(process); } }; function spoofPlatform(p = 'Mac') { try { Object.defineProperty(navigator, 'platform', { get: () => p, configurable: true, enumerable: true }); } catch (e) { /* ignore */ } } StorageManager.loadConfig(); if (currentConfig.spoofUAEnabled) spoofPlatform('Mac'); function suppressUIForIframe() { if (!currentConfig.iframeUIFix) return false; try { return _globals.self !== _globals.top; } catch (e) { return true; } } function initModulesWithoutUI() { if (!UIController.initialized) { UIController.initialized = true; UIController.applyInitialModuleStates(); UIController.createModules(); UIController.applyModuleSettings(); UIController.setupObservers(); UIController.setupResourceScan(); const any = Object.values(currentConfig.modules).some(v => v === true); if (currentConfig.residualCleanupEnabled && any) ResidualCleaner.init(); CSSUniversalHider.init(); } } function resetAllCachesAndStates() { if (centralScheduler) centralScheduler.clearCache(); ProcessedElementsCache.clear(); LogManager.clearLoggedIdentifiers(); urlCache.clear(); } function safeInit() { if (_document.documentElement) { if (suppressUIForIframe()) initModulesWithoutUI(); else UIController.init(); 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()) { if (suppressUIForIframe()) initModulesWithoutUI(); else UIController.init(); } }, 5000); } })();