// ==UserScript== // @name 小说漫画网页广告拦截器 // @namespace http://tampermonkey.net/ // @version 4.3.0 // @author DeepSeek&Gemini // @description 一个手机端via浏览器能用的强大的广告拦截器 // @match *://*/* // @license MIT // @grant unsafeWindow // @grant GM_setValue // @grant GM_getValue // @grant GM_registerMenuCommand // @grant GM_notification // @grant GM_xmlhttpRequest // @run-at document-start // ==/UserScript== (function() { 'use strict'; const DEFAULT_MODULE_STATE = { specialUA: false, removeInlineScripts: false, removeExternalScripts: false, interceptThirdPartyResources: false, manageCSP: false, }; const MODULE_NAMES = { specialUA: '添加特殊UA', removeInlineScripts: '移除内嵌脚本', removeExternalScripts: '移除外联脚本', interceptThirdPartyResources: '拦截第三方资源', manageCSP: 'CSP策略管理', }; const DEFAULT_CSP_RULES_TEMPLATE = [ { id: 1, name: '仅允许同源脚本', rule: "script-src 'self'", enabled: true }, { id: 2, name: '禁止内联脚本', rule: "script-src 'unsafe-inline'", enabled: false }, { id: 3, name: '禁止eval执行', rule: "script-src 'unsafe-eval'", enabled: false }, { id: 4, name: '阻止外部样式加载', rule: "style-src 'self'", enabled: false }, { id: 5, name: '阻止内联样式执行', rule: "style-src 'unsafe-inline'", enabled: false }, { id: 6, name: '阻止外部图片加载', rule: "img-src 'self'", enabled: true }, { id: 7, name: '禁止所有框架加载', rule: "frame-src 'none'", enabled: false }, { id: 8, name: '阻止媒体资源加载', rule: "media-src 'none'", enabled: false }, { id: 9, name: '阻止对象嵌入', rule: "object-src 'none'", enabled: false } ]; const CONFIG_STORAGE_KEY_PREFIX = `customAdBlockerConfig_`; let currentConfig = { modules: { ...DEFAULT_MODULE_STATE }, cspRules: DEFAULT_CSP_RULES_TEMPLATE.map(rule => ({ ...rule })), whitelist: {}, }; const Utils = { truncateString(str, maxLength) { if (typeof str !== 'string') return ''; return str.length <= maxLength ? str : str.slice(0, maxLength) + '...'; }, getCurrentHostname() { return location.hostname; }, isElement(el) { return el instanceof Element; }, getScriptContentPreview(scriptElement) { if (!scriptElement || scriptElement.tagName !== 'SCRIPT') return ''; return Utils.truncateString(scriptElement.textContent.replace(/\s+/g, ' '), 100); }, getIframeSrcPreview(iframeElement) { if (!iframeElement || iframeElement.tagName !== 'IFRAME') return ''; return Utils.truncateString(iframeElement.src, 100); }, getResourceHostname(url) { if (!url || typeof url !== 'string') return null; if (url.startsWith('data:') || url.startsWith('blob:') || url.startsWith('about:blank')) return null; try { return new URL(url, location.href).hostname; } catch (e) { return null; } }, getDomain(hostname) { if (!hostname) return null; const parts = hostname.split('.'); return parts.length <= 2 ? hostname : parts.slice(-2).join('.'); }, isThirdPartyHost(resourceHostname, currentHost) { if (!resourceHostname) return false; const currentHostDomain = Utils.getDomain(currentHost); const resourceHostDomain = Utils.getDomain(resourceHostname); return !(!currentHostDomain || !resourceHostDomain || resourceHostDomain === currentHostDomain); }, getAbsoluteURL(url) { if (!url) return ''; try { return new URL(url, location.href).href; } catch (e) { return url; } }, getContentIdentifier(element, reasonType = null) { if (!element || !Utils.isElement(element)) { if (reasonType && typeof reasonType.detail === 'string') { if (reasonType.detail.startsWith('SRC:')) { return `${reasonType.type || 'INTERCEPTED'}_SRC: ${Utils.truncateString(reasonType.detail.substring(4).trim(), 100)}`; } else if (reasonType.detail.startsWith('URL:')) { return `${reasonType.type || 'INTERCEPTED'}_URL: ${Utils.truncateString(reasonType.detail.substring(5).trim(), 100)}`; } else if (reasonType.type === 'EVAL') { return `EVAL_CODE: ${Utils.truncateString(reasonType.detail, 100)}`; } else if (reasonType.type === 'FUNCTION_CONSTRUCTOR') { return `FUNCTION_CODE: ${Utils.truncateString(reasonType.detail, 100)}`; } return `LOG_DETAIL: ${Utils.truncateString(reasonType.detail, 100)}`; } return null; } const tagName = element.tagName; const src = element.src || element.getAttribute('data-src') || element.href || element.action || ''; if (tagName === 'SCRIPT') { return element.src ? `SCRIPT_SRC: ${Utils.truncateString(element.src, 100)}` : `SCRIPT_CONTENT: ${Utils.getScriptContentPreview(element)}`; } else if (tagName === 'IFRAME') { return `IFRAME_SRC: ${Utils.truncateString(element.src, 100)}`; } else if (tagName === 'IMG') { return src ? `IMG_SRC: ${Utils.truncateString(src, 100)}` : null; } else if (tagName === 'A') { return src ? `A_HREF: ${Utils.truncateString(src, 100)}` : null; } else if (tagName === 'LINK' && element.rel === 'stylesheet' && element.href) { return `CSS_HREF: ${Utils.truncateString(element.href, 100)}`; } else if (['VIDEO', 'AUDIO', 'SOURCE'].includes(tagName) && src) { return `${tagName}_SRC: ${Utils.truncateString(src, 100)}`; } return null; } }; const LogManager = { logs: [], maxLogs: 100, logEntryData: {}, loggedContentIdentifiers: new Set(), add(moduleKey, element, reason) { if (!currentConfig.modules.interceptThirdPartyResources && !currentConfig.modules.removeInlineScripts && !currentConfig.modules.removeExternalScripts) { return; } if (!Utils.isElement(element) && element !== null && typeof reason !== 'object') return; const currentDomain = Utils.getCurrentHostname(); if (Whitelisting.isElementWhitelisted(element) || Whitelisting.isReasonWhitelisted(reason)) { return; } let elementIdentifier = '[未知元素]'; let interceptedContent = '[无法获取内容]'; let contentIdentifier = null; 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') { interceptedContent = element.src ? `SRC: ${Utils.truncateString(element.src, 100)}` : Utils.getScriptContentPreview(element); } else if (tagName === 'IFRAME') { interceptedContent = Utils.getIframeSrcPreview(element); } else if (tagName === 'IMG') { const src = element.src || element.dataset.src; interceptedContent = Utils.truncateString(src || '', 100); } else if (tagName === 'A') { interceptedContent = Utils.truncateString(element.href || '', 100); } else if (tagName === 'LINK' && element.rel === 'stylesheet') { interceptedContent = Utils.truncateString(element.href || '', 100); } else if (['VIDEO', 'AUDIO', 'SOURCE'].includes(tagName)) { interceptedContent = Utils.truncateString(element.src || '', 100); } else { interceptedContent = Utils.truncateString(element.outerHTML, 100); } } else if (reason && typeof reason.detail === 'string') { interceptedContent = Utils.truncateString(reason.detail, 100); elementIdentifier = reason.type ? `[${reason.type}]` : '[未知类型]'; contentIdentifier = Utils.getContentIdentifier(null, reason); } if (!contentIdentifier) { return; } if (this.loggedContentIdentifiers.has(contentIdentifier)) { return; } const logId = this.logs.length + 1; this.logs.push({ id: logId, module: MODULE_NAMES[moduleKey] || moduleKey, element: elementIdentifier, content: interceptedContent, }); this.logEntryData[logId] = { contentIdentifier: contentIdentifier, element: element, reason: reason, }; this.loggedContentIdentifiers.add(contentIdentifier); if (this.logs.length > this.maxLogs) { const removedLogEntry = this.logs.shift(); const removedEntryInfo = this.logEntryData[removedLogEntry.id]; if (removedEntryInfo) { this.loggedContentIdentifiers.delete(removedEntryInfo.contentIdentifier); delete this.logEntryData[removedLogEntry.id]; } } }, showInAlert() { const currentDomain = Utils.getCurrentHostname(); const logEntries = this.logs.map(log => `序号: ${log.id}\n` + `模块: ${log.module}\n` + `元素: ${log.element}\n` + `内容: ${log.content}` ).join('\n\n'); const promptMessage = `广告拦截日志(最近${this.logs.length}条):\n\n${logEntries || '暂无日志'}\n\n` + `添加白名单方式:\n` + `1. 输入序号(如 1-3, 1,3,5)\n` + `2. 输入关键词(如 aaa, bbb)\n` + `3. 输入 0 清空当前域名所有白名单\n\n` + `请输入:`; let input = prompt(promptMessage, ""); if (input === null) return; input = input.trim(); if (input === "0") { if (confirm(`清空 ${currentDomain} 的所有白名单?`)) { Whitelisting.clearDomainWhitelist(currentDomain); StorageManager.saveConfig(); alert("白名单已清空,页面将刷新。"); location.reload(); } } else { const indicesToWhitelist = new Set(); const keywordsToWhitelist = new Set(); const parts = input.replace(/,/g, ',').split(/[\s,]+/); parts.forEach(part => { if (part.includes('-')) { const range = part.split('-').map(Number); if (range.length === 2 && !isNaN(range[0]) && !isNaN(range[1])) { const start = Math.min(range[0], range[1]); const end = Math.max(range[0], range[1]); for (let i = start; i <= end; i++) { indicesToWhitelist.add(i); } } } else { const num = parseInt(part, 10); if (!isNaN(num)) { indicesToWhitelist.add(num); } else if (part.length > 0) { keywordsToWhitelist.add(part.toLowerCase()); } } }); let addedCount = 0; let whitelistedIdentifiers = new Set(); indicesToWhitelist.forEach(index => { const logEntryInfo = this.logEntryData[index]; if (logEntryInfo && logEntryInfo.contentIdentifier) { const { contentIdentifier } = logEntryInfo; if (!Whitelisting.isContentWhitelisted(currentDomain, contentIdentifier)) { whitelistedIdentifiers.add(contentIdentifier); } } }); keywordsToWhitelist.forEach(keyword => { Object.values(this.logEntryData).forEach(logEntryInfo => { if (logEntryInfo.contentIdentifier && logEntryInfo.contentIdentifier.toLowerCase().includes(keyword)) { if (!Whitelisting.isContentWhitelisted(currentDomain, logEntryInfo.contentIdentifier)) { whitelistedIdentifiers.add(logEntryInfo.contentIdentifier); } } }); }); whitelistedIdentifiers.forEach(identifier => { Whitelisting.add(currentDomain, identifier); addedCount++; }); if (addedCount > 0) { StorageManager.saveConfig(); alert(`${addedCount} 项已添加到白名单,页面将刷新。`); location.reload(); } else if (input.length > 0) { alert("未找到匹配项,或已在白名单中。"); } } } }; const Whitelisting = { isElementWhitelisted(element) { if (!element || !Utils.isElement(element)) return false; const currentDomain = Utils.getCurrentHostname(); const contentIdentifier = Utils.getContentIdentifier(element); return !!(contentIdentifier && currentDomain && currentConfig.whitelist[currentDomain] && currentConfig.whitelist[currentDomain].has(contentIdentifier)); }, isReasonWhitelisted(reason) { if (!reason || typeof reason.detail !== 'string') return false; const currentDomain = Utils.getCurrentHostname(); const contentIdentifier = Utils.getContentIdentifier(null, reason); return !!(contentIdentifier && currentDomain && currentConfig.whitelist[currentDomain] && currentConfig.whitelist[currentDomain].has(contentIdentifier)); }, isContentWhitelisted(domain, contentIdentifier) { if (!domain || !contentIdentifier) return false; return !!(currentConfig.whitelist[domain] && currentConfig.whitelist[domain].has(contentIdentifier)); }, add(domain, contentIdentifier) { if (!domain || !contentIdentifier || contentIdentifier.trim() === '') return; if (!currentConfig.whitelist[domain]) { currentConfig.whitelist[domain] = new Set(); } currentConfig.whitelist[domain].add(contentIdentifier); }, clearDomainWhitelist(domain) { if (currentConfig.whitelist[domain]) { currentConfig.whitelist[domain].clear(); } }, clearAllWhitelists() { currentConfig.whitelist = {}; } }; const StorageManager = { getConfigKey(hostname) { return `${CONFIG_STORAGE_KEY_PREFIX}${hostname}`; }, loadConfig() { const hostname = Utils.getCurrentHostname(); const key = this.getConfigKey(hostname); try { const savedConfig = JSON.parse(GM_getValue(key, '{}')); if (savedConfig) { if (savedConfig.modules) { Object.assign(currentConfig.modules, savedConfig.modules); } if (savedConfig.cspRules) { currentConfig.cspRules = savedConfig.cspRules.map(rule => ({ ...rule })); } if (savedConfig.whitelist) { currentConfig.whitelist = {}; for (const domain in savedConfig.whitelist) { if (Array.isArray(savedConfig.whitelist[domain])) { currentConfig.whitelist[domain] = new Set(savedConfig.whitelist[domain]); } } } } } catch (e) { Object.assign(currentConfig.modules, DEFAULT_MODULE_STATE); currentConfig.cspRules = DEFAULT_CSP_RULES_TEMPLATE.map(rule => ({ ...rule })); currentConfig.whitelist = {}; } Object.keys(DEFAULT_MODULE_STATE).forEach(key => { if (currentConfig.modules[key] === undefined) { currentConfig.modules[key] = DEFAULT_MODULE_STATE[key]; } }); if (currentConfig.modules.specialUA === undefined) currentConfig.modules.specialUA = true; if (currentConfig.modules.manageCSP === undefined) currentConfig.modules.manageCSP = false; }, saveConfig() { const hostname = Utils.getCurrentHostname(); const key = this.getConfigKey(hostname); try { const whitelistForStorage = {}; for (const domain in currentConfig.whitelist) { whitelistForStorage[domain] = Array.from(currentConfig.whitelist[domain]); } GM_setValue(key, JSON.stringify({ modules: currentConfig.modules, cspRules: currentConfig.cspRules, whitelist: whitelistForStorage })); } catch (e) {} } }; const SpecialUAModule = { originalNavigator: window.navigator, fakeUA: 'UCWEB/2.0 Mozilla/5.0 (SymbianOS/9.3; Series60/3.2 NokiaE5-00.2/071.003; Profile/MIDP-2.1 Configuration/CLDC-1.1) NokiaBrowser/7.3.1.26 Mobile Safari/533.4 3gpp-gba AppleWebCore/2.0 Device/Nokia-E5-00.2 NetType/2G CPU/ARM9 Screen/320x240', fakePlatform: 'Symbian OS', fakeAppVersion: 'UCWEB/2.0', navigatorProxy: null, originalDescriptor: null, init() { if (currentConfig.modules.specialUA) { this.enable(); } else { this.disable(); } }, enable() { if (!this.navigatorProxy) { this.navigatorProxy = new Proxy(this.originalNavigator, { get: (target, prop) => { if (prop === 'userAgent') return this.fakeUA; if (prop === 'platform') return this.fakePlatform; if (prop === 'appVersion') return this.fakeAppVersion; return Reflect.get(target, prop); } }); } if (window.navigator !== this.navigatorProxy) { try { this.originalDescriptor = Object.getOwnPropertyDescriptor(window, 'navigator'); Object.defineProperty(window, 'navigator', { value: this.navigatorProxy, configurable: true, writable: this.originalDescriptor ? this.originalDescriptor.writable : false }); } catch (e) {} } }, disable() { if (this.navigatorProxy && window.navigator === this.navigatorProxy) { try { if (this.originalDescriptor) { Object.defineProperty(window, 'navigator', this.originalDescriptor); } else { Object.defineProperty(window, 'navigator', { value: this.originalNavigator, configurable: true, writable: false }); } } catch (e) {} } }, check(element) { return false; } }; const ProcessedElementsCache = { _processedElements: new WeakSet(), isProcessed(element) { if (!Utils.isElement(element)) return false; return this._processedElements.has(element) || element.dataset.adblockProcessed === 'true'; }, markAsProcessed(element) { if (!Utils.isElement(element)) return; this._processedElements.add(element); element.dataset.adblockProcessed = 'true'; }, clear() { this._processedElements = new WeakSet(); } }; const ResourceCanceller = { cancelResourceLoading(element) { if (!Utils.isElement(element) || ProcessedElementsCache.isProcessed(element)) return; const tagName = element.tagName; if (['IMG', 'VIDEO', 'AUDIO', 'SOURCE'].includes(tagName) && element.src) { element.src = ''; element.srcset = ''; element.removeAttribute('srcset'); if (element.load) element.load(); } else if (tagName === 'IFRAME' && element.src) { element.src = 'about:blank'; } else if (tagName === 'SCRIPT' && element.src) { element.src = ''; } else if (tagName === 'LINK' && element.rel === 'stylesheet' && element.href) { element.href = ''; } if (element.parentNode) { element.parentNode.removeChild(element); } } }; const RemoveInlineScriptsModule = { mutationObserver: null, init() { if (currentConfig.modules.removeInlineScripts) { this.enable(); } else { this.disable(); } }, enable() { this.mutationObserver = new MutationObserver(mutations => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'SCRIPT' && !node.src && !ProcessedElementsCache.isProcessed(node)) { const contentIdentifier = Utils.getContentIdentifier(node); if (contentIdentifier && !Whitelisting.isContentWhitelisted(Utils.getCurrentHostname(), contentIdentifier)) { LogManager.add('removeInlineScripts', node, { type: '内嵌脚本移除', detail: `内容: ${Utils.getScriptContentPreview(node)}` }); ProcessedElementsCache.markAsProcessed(node); node.remove(); } } } } }); this.mutationObserver.observe(document.documentElement, { childList: true, subtree: true }); document.querySelectorAll('script:not([src])').forEach(script => { if (ProcessedElementsCache.isProcessed(script)) return; const contentIdentifier = Utils.getContentIdentifier(script); if (contentIdentifier && !Whitelisting.isContentWhitelisted(Utils.getCurrentHostname(), contentIdentifier)) { LogManager.add('removeInlineScripts', script, { type: '内嵌脚本移除', detail: `内容: ${Utils.getScriptContentPreview(script)}` }); ProcessedElementsCache.markAsProcessed(script); script.remove(); } }); }, disable() { if (this.mutationObserver) { this.mutationObserver.disconnect(); this.mutationObserver = null; } }, check(element) { if (!currentConfig.modules.removeInlineScripts || ProcessedElementsCache.isProcessed(element)) return false; if (element.tagName === 'SCRIPT' && !element.src) { const contentIdentifier = Utils.getContentIdentifier(element); if (contentIdentifier && !Whitelisting.isContentWhitelisted(Utils.getCurrentHostname(), contentIdentifier)) { LogManager.add('removeInlineScripts', element, { type: '内嵌脚本移除', detail: `内容: ${Utils.getScriptContentPreview(element)}` }); ProcessedElementsCache.markAsProcessed(element); return true; } } return false; } }; const RemoveExternalScriptsModule = { mutationObserver: null, init() { if (currentConfig.modules.removeExternalScripts) { this.enable(); } else { this.disable(); } }, enable() { this.mutationObserver = new MutationObserver(mutations => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'SCRIPT' && node.src && !ProcessedElementsCache.isProcessed(node)) { const contentIdentifier = Utils.getContentIdentifier(node); if (contentIdentifier && !Whitelisting.isContentWhitelisted(Utils.getCurrentHostname(), contentIdentifier)) { LogManager.add('removeExternalScripts', node, { type: '外联脚本移除', detail: `SRC: ${Utils.truncateString(node.src, 100)}` }); ResourceCanceller.cancelResourceLoading(node); ProcessedElementsCache.markAsProcessed(node); } } } } }); this.mutationObserver.observe(document.documentElement, { childList: true, subtree: true }); document.querySelectorAll('script[src]').forEach(script => { if (ProcessedElementsCache.isProcessed(script)) return; const contentIdentifier = Utils.getContentIdentifier(script); if (contentIdentifier && !Whitelisting.isContentWhitelisted(Utils.getCurrentHostname(), contentIdentifier)) { LogManager.add('removeExternalScripts', script, { type: '外联脚本移除', detail: `SRC: ${Utils.truncateString(script.src, 100)}` }); ResourceCanceller.cancelResourceLoading(script); ProcessedElementsCache.markAsProcessed(script); } }); }, disable() { if (this.mutationObserver) { this.mutationObserver.disconnect(); this.mutationObserver = null; } }, check(element) { if (!currentConfig.modules.removeExternalScripts || ProcessedElementsCache.isProcessed(element)) return false; if (element.tagName === 'SCRIPT' && element.src) { const contentIdentifier = Utils.getContentIdentifier(element); if (contentIdentifier && !Whitelisting.isContentWhitelisted(Utils.getCurrentHostname(), contentIdentifier)) { LogManager.add('removeExternalScripts', element, { type: '外联脚本移除', detail: `SRC: ${Utils.truncateString(element.src, 100)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return true; } } return false; } }; const ThirdPartyModule = { originalFetch: null, originalXhrOpen: null, originalXhrSend: null, originalCreateElement: null, originalAppendChild: null, originalDocumentWrite: null, originalEval: null, originalFunction: null, init() { if (currentConfig.modules.interceptThirdPartyResources) { this.enable(); } else { this.disable(); } }, enable() { const cspBlockEval = currentConfig.cspRules.find(rule => rule.id === 3 && rule.enabled); if (!cspBlockEval) { this.originalEval = unsafeWindow.eval; unsafeWindow.eval = (code) => { const contentIdentifier = Utils.getContentIdentifier(null, { type: 'EVAL', detail: code }); if (contentIdentifier && !Whitelisting.isContentWhitelisted(Utils.getCurrentHostname(), contentIdentifier)) { LogManager.add('interceptThirdPartyResources', null, { type: 'EVAL拦截', detail: `代码: ${Utils.truncateString(code, 100)}` }); return undefined; } return this.originalEval.call(unsafeWindow, code); }; } const cspBlockFunction = currentConfig.cspRules.find(rule => rule.id === 3 && rule.enabled); if (!cspBlockFunction) { this.originalFunction = unsafeWindow.Function; unsafeWindow.Function = function(...args) { const code = args.length > 0 ? args[args.length - 1] : ''; const contentIdentifier = Utils.getContentIdentifier(null, { type: 'FUNCTION_CONSTRUCTOR', detail: code }); if (contentIdentifier && !Whitelisting.isContentWhitelisted(Utils.getCurrentHostname(), contentIdentifier)) { LogManager.add('interceptThirdPartyResources', null, { type: 'Function构造拦截', detail: `代码: ${Utils.truncateString(code, 100)}` }); return () => {}; } return this.originalFunction.apply(unsafeWindow, args); }; } this.originalFetch = window.fetch; window.fetch = (input, init) => { if (!currentConfig.modules.interceptThirdPartyResources) { return this.originalFetch.call(this, input, init); } const url = typeof input === 'string' ? input : input.url; const resourceURL = Utils.getAbsoluteURL(url); const resourceHostname = Utils.getResourceHostname(resourceURL); const currentHost = Utils.getCurrentHostname(); const contentIdentifier = Utils.getContentIdentifier(null, { type: 'FETCH', detail: `URL: ${Utils.truncateString(resourceURL, 100)}` }); if (resourceHostname && Utils.isThirdPartyHost(resourceHostname, currentHost)) { if (contentIdentifier && !Whitelisting.isContentWhitelisted(currentHost, contentIdentifier)) { LogManager.add('interceptThirdPartyResources', null, { type: '第三方请求拦截', detail: `URL: ${Utils.truncateString(resourceURL, 100)}` }); return Promise.reject(new Error('Third-party resource blocked by AdBlocker.')); } } return this.originalFetch.call(this, input, init); }; this.originalXhrOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url) { if (!currentConfig.modules.interceptThirdPartyResources) { return this.originalXhrOpen.apply(this, arguments); } const resourceURL = Utils.getAbsoluteURL(url); const resourceHostname = Utils.getResourceHostname(resourceURL); const currentHost = Utils.getCurrentHostname(); const contentIdentifier = Utils.getContentIdentifier(null, { type: 'XHR', detail: `URL: ${Utils.truncateString(resourceURL, 100)}` }); if (resourceHostname && Utils.isThirdPartyHost(resourceHostname, currentHost)) { if (contentIdentifier && !Whitelisting.isContentWhitelisted(currentHost, contentIdentifier)) { LogManager.add('interceptThirdPartyResources', null, { type: '第三方请求拦截', detail: `URL: ${Utils.truncateString(resourceURL, 100)}` }); this._adblockBlocked = true; return; } } return this.originalXhrOpen.apply(this, arguments); }; this.originalXhrSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function() { if (this._adblockBlocked) { return; } this.originalXhrSend.apply(this, arguments); }; this.originalCreateElement = document.createElement; document.createElement = (tagName, options) => { const element = this.originalCreateElement.call(document, tagName, options); if (!currentConfig.modules.interceptThirdPartyResources || ProcessedElementsCache.isProcessed(element)) { return element; } const resourceURL = Utils.getAbsoluteURL(element.src || element.getAttribute('data-src') || element.href || element.action); if (resourceURL) { const resourceHostname = Utils.getResourceHostname(resourceURL); const currentHost = Utils.getCurrentHostname(); const contentIdentifier = Utils.getContentIdentifier(element); if (resourceHostname && Utils.isThirdPartyHost(resourceHostname, currentHost)) { if (contentIdentifier && !Whitelisting.isContentWhitelisted(currentHost, contentIdentifier)) { LogManager.add('interceptThirdPartyResources', element, { type: '第三方资源拦截', detail: `SRC: ${Utils.truncateString(resourceURL, 100)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return element; } } } return element; }; this.originalAppendChild = Node.prototype.appendChild; Node.prototype.appendChild = function(node) { if (!currentConfig.modules.interceptThirdPartyResources || !Utils.isElement(node) || ProcessedElementsCache.isProcessed(node)) { return this.originalAppendChild.call(this, node); } const resourceURL = Utils.getAbsoluteURL(node.src || node.getAttribute('data-src') || node.href || node.action); if (resourceURL) { const resourceHostname = Utils.getResourceHostname(resourceURL); const currentHost = Utils.getCurrentHostname(); const contentIdentifier = Utils.getContentIdentifier(node); if (resourceHostname && Utils.isThirdPartyHost(resourceHostname, currentHost)) { if (contentIdentifier && !Whitelisting.isContentWhitelisted(currentHost, contentIdentifier)) { LogManager.add('interceptThirdPartyResources', node, { type: '第三方资源拦截', detail: `SRC: ${Utils.truncateString(resourceURL, 100)}` }); ResourceCanceller.cancelResourceLoading(node); ProcessedElementsCache.markAsProcessed(node); return node; } } } return this.originalAppendChild.call(this, node); }; this.originalDocumentWrite = document.write; document.write = function(content) { if (!currentConfig.modules.interceptThirdPartyResources) { return this.originalDocumentWrite.call(document, content); } const tempDiv = document.createElement('div'); tempDiv.innerHTML = content; const scripts = tempDiv.querySelectorAll('script[src]'); let modifiedContent = content; for (const script of scripts) { const src = script.src; if (src) { const resourceURL = Utils.getAbsoluteURL(src); const resourceHostname = Utils.getResourceHostname(resourceURL); const currentHost = Utils.getCurrentHostname(); const contentIdentifier = Utils.getContentIdentifier(script); if (resourceHostname && Utils.isThirdPartyHost(resourceHostname, currentHost)) { if (contentIdentifier && !Whitelisting.isContentWhitelisted(currentHost, contentIdentifier)) { LogManager.add('interceptThirdPartyResources', script, { type: '第三方脚本通过document.write拦截', detail: `SRC: ${Utils.truncateString(resourceURL, 100)}` }); ResourceCanceller.cancelResourceLoading(script); ProcessedElementsCache.markAsProcessed(script); } } } } modifiedContent = tempDiv.innerHTML; this.originalDocumentWrite.call(document, modifiedContent); }.bind(this); }, disable() { if (this.originalFetch) window.fetch = this.originalFetch; if (this.originalXhrOpen) XMLHttpRequest.prototype.open = this.originalXhrOpen; if (this.originalXhrSend) XMLHttpRequest.prototype.send = this.originalXhrSend; if (this.originalCreateElement) document.createElement = this.originalCreateElement; if (this.originalAppendChild) Node.prototype.appendChild = this.originalAppendChild; if (this.originalDocumentWrite) document.write = this.originalDocumentWrite; if (this.originalEval) unsafeWindow.eval = this.originalEval; if (this.originalFunction) unsafeWindow.Function = this.originalFunction; }, check(element) { if (!currentConfig.modules.interceptThirdPartyResources || !Utils.isElement(element) || ProcessedElementsCache.isProcessed(element)) return false; const resourceURL = Utils.getAbsoluteURL(element.src || element.getAttribute('data-src') || element.href || element.action); if (resourceURL) { const resourceHostname = Utils.getResourceHostname(resourceURL); const currentHost = Utils.getCurrentHostname(); const contentIdentifier = Utils.getContentIdentifier(element); if (resourceHostname && Utils.isThirdPartyHost(resourceHostname, currentHost)) { if (contentIdentifier && !Whitelisting.isContentWhitelisted(currentHost, contentIdentifier)) { LogManager.add('interceptThirdPartyResources', element, { type: '第三方资源拦截', detail: `SRC: ${Utils.truncateString(resourceURL, 100)}` }); ResourceCanceller.cancelResourceLoading(element); ProcessedElementsCache.markAsProcessed(element); return true; } } } return false; } }; const CSPModule = { init() {}, applyCSP() { if (!currentConfig.modules.manageCSP) return; const existingMeta = document.querySelector('meta[http-equiv="Content-Security-Policy"]'); if (existingMeta) { existingMeta.remove(); } const enabledRules = currentConfig.cspRules.filter(rule => rule.enabled); if (enabledRules.length === 0) { return; } const policyString = enabledRules.map(rule => rule.rule).join('; '); const meta = document.createElement('meta'); meta.httpEquiv = "Content-Security-Policy"; meta.content = policyString; if (document.head) { document.head.appendChild(meta); } else { document.documentElement.prepend(meta); } }, removeCSP() { const existingMeta = document.querySelector('meta[http-equiv="Content-Security-Policy"]'); if (existingMeta) { existingMeta.remove(); } }, updateRule(ruleId, enabled) { const rule = currentConfig.cspRules.find(r => r.id === ruleId); if (rule) { rule.enabled = enabled; } }, showManagementPanel() { const ruleDescriptions = currentConfig.cspRules.map(r => ({ id: r.id, name: r.name, description: this.getRuleDescription(r), enabled: r.enabled })); const rulesDisplay = ruleDescriptions .map(r => `${r.id}. ${r.name} (${r.enabled ? '✅启用' : '❌禁用'})`) .join('\n'); const promptMessage = `CSP策略管理:\n` + `状态: ${currentConfig.modules.manageCSP ? '启用' : '禁用'}\n\n` + `可用规则:\n${rulesDisplay}\n\n` + `操作指令:\n` + `enable - 启用CSP\n` + `disable - 禁用CSP\n` + `1on - 启用规则1\n` + `23off - 禁用规则2和3\n` + `allon - 启用所有规则\n` + `alloff - 禁用所有规则\n\n` + `请输入指令:`; let input = prompt(promptMessage, ""); if (input === null) return; input = input.trim().toLowerCase(); let needsReload = false; if (input === 'enable') { currentConfig.modules.manageCSP = true; this.applyCSP(); needsReload = true; } else if (input === 'disable') { currentConfig.modules.manageCSP = false; this.removeCSP(); needsReload = true; } else if (input === 'allon') { currentConfig.cspRules.forEach(rule => rule.enabled = true); if (currentConfig.modules.manageCSP) this.applyCSP(); needsReload = true; } else if (input === 'alloff') { currentConfig.cspRules.forEach(rule => rule.enabled = false); if (currentConfig.modules.manageCSP) this.removeCSP(); needsReload = true; } else if (/^(\d+|all)(\d*on|off)$/.test(input)) { const match = input.match(/^(\d+|all)(\d*on|off)$/); if (match) { const ruleSpec = match[1]; const action = match[2]; const enable = action.endsWith('on'); let ruleIdsToModify = []; if (ruleSpec === 'all') { ruleIdsToModify = currentConfig.cspRules.map(r => r.id); } else { for (const char of ruleSpec) { const id = parseInt(char, 10); if (!isNaN(id)) ruleIdsToModify.push(id); } } let modified = false; ruleIdsToModify.forEach(id => { const rule = currentConfig.cspRules.find(r => r.id === id); if (rule && rule.enabled !== enable) { rule.enabled = enable; modified = true; } }); if (modified) { if (currentConfig.modules.manageCSP) this.applyCSP(); needsReload = true; } else { alert("未找到指定规则。"); } } else { alert("无效格式。"); } } else { alert("无效指令。"); } if (needsReload) { StorageManager.saveConfig(); location.reload(); } }, getRuleDescription(rule) { const descriptions = { 1: "只允许本网站脚本", 2: "禁止页面内脚本", 3: "禁止eval执行代码", 4: "只允许本网站样式", 5: "禁止页面内样式", 6: "只允许本网站图片", 7: "禁止框架加载", 8: "禁止媒体加载", 9: "禁止对象嵌入" }; return descriptions[rule.id] || "无描述"; } }; const UIController = { mutationObserver: null, throttledMutationHandler: null, init() { StorageManager.loadConfig(); this.applyInitialModuleStates(); this.registerMenuCommands(); this.applyModuleSettings(); this.setupObservers(); }, applyInitialModuleStates() { Object.keys(DEFAULT_MODULE_STATE).forEach(key => { if (currentConfig.modules[key] === undefined) { currentConfig.modules[key] = DEFAULT_MODULE_STATE[key]; } }); if (currentConfig.modules.specialUA === undefined) { currentConfig.modules.specialUA = true; } if (currentConfig.modules.manageCSP === undefined) { currentConfig.modules.manageCSP = false; } }, registerMenuCommands() { GM_registerMenuCommand(`🔘 广告拦截 [${this.isAnyModuleEnabled() ? '✅' : '❌'}]`, () => this.toggleAllModules()); Object.keys(MODULE_NAMES).forEach(key => { GM_registerMenuCommand( `${MODULE_NAMES[key]} [${currentConfig.modules[key] ? '✅' : '❌'}]`, () => this.toggleModule(key) ); }); GM_registerMenuCommand('📜 查看拦截日志', () => LogManager.showInAlert()); GM_registerMenuCommand('🚫 清空当前域名白名单', () => { const currentDomain = Utils.getCurrentHostname(); if (confirm(`确定清空当前域名 (${currentDomain}) 的白名单吗?`)) { Whitelisting.clearDomainWhitelist(currentDomain); StorageManager.saveConfig(); alert("当前域名的白名单已清空。页面将刷新。"); location.reload(); } }); GM_registerMenuCommand('🛡️ CSP策略管理', () => CSPModule.showManagementPanel()); GM_registerMenuCommand('🔄 重置所有设置', () => this.resetSettings()); }, isAnyModuleEnabled() { return Object.keys(MODULE_NAMES).some(key => currentConfig.modules[key]); }, toggleAllModules() { const newState = !this.isAnyModuleEnabled(); Object.keys(MODULE_NAMES).forEach(key => { currentConfig.modules[key] = newState; }); this.applyModuleSettings(); StorageManager.saveConfig(); location.reload(); }, toggleModule(key) { currentConfig.modules[key] = !currentConfig.modules[key]; this.applyModuleSettings(); StorageManager.saveConfig(); location.reload(); }, applyModuleSettings() { SpecialUAModule.init(); RemoveInlineScriptsModule.init(); RemoveExternalScriptsModule.init(); ThirdPartyModule.init(); CSPModule.init(); }, setupObservers() { const relevantModulesEnabled = Object.keys(MODULE_NAMES).some(key => currentConfig.modules[key] && ( key === 'removeInlineScripts' || key === 'removeExternalScripts' || key === 'interceptThirdPartyResources' ) ); if (!relevantModulesEnabled) return; this.throttledMutationHandler = this.throttle(this.handleMutations, 50); this.mutationObserver = new MutationObserver(mutations => { this.throttledMutationHandler(mutations); }); this.mutationObserver.observe(document.documentElement, { childList: true, subtree: true, }); const processExistingElements = () => { const elementsToProcess = new Set(document.querySelectorAll('script, iframe, img, a, link, form, video, audio, source')); document.querySelectorAll('img[data-src]').forEach(el => elementsToProcess.add(el)); elementsToProcess.forEach(el => { if (!ProcessedElementsCache.isProcessed(el)) { if (currentConfig.modules.removeInlineScripts && el.tagName === 'SCRIPT' && !el.src) { if (RemoveInlineScriptsModule.check(el)) el.remove(); } if (currentConfig.modules.removeExternalScripts && el.tagName === 'SCRIPT' && el.src) { if (RemoveExternalScriptsModule.check(el)) ResourceCanceller.cancelResourceLoading(el); } if (currentConfig.modules.interceptThirdPartyResources) { if (ThirdPartyModule.check(el)) ResourceCanceller.cancelResourceLoading(el); } } }); }; processExistingElements(); }, handleMutations(mutations) { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.nodeType === Node.ELEMENT_NODE && !ProcessedElementsCache.isProcessed(node)) { if (node.tagName === 'SCRIPT') { if (currentConfig.modules.removeInlineScripts && !node.src) { if (RemoveInlineScriptsModule.check(node)) node.remove(); } else if (currentConfig.modules.removeExternalScripts && node.src) { if (RemoveExternalScriptsModule.check(node)) ResourceCanceller.cancelResourceLoading(node); } else if (currentConfig.modules.interceptThirdPartyResources) { if (ThirdPartyModule.check(node)) ResourceCanceller.cancelResourceLoading(node); } } if (currentConfig.modules.interceptThirdPartyResources) { if (ThirdPartyModule.check(node)) ResourceCanceller.cancelResourceLoading(node); } } } } }, throttle(func, delay) { let inThrottle; return function(...args) { const context = this; if (!inThrottle) { inThrottle = true; setTimeout(() => inThrottle = false, delay); func.apply(context, args); } }; }, resetSettings() { if (confirm("确定要重置所有设置吗?这将清除所有配置和白名单。")) { Object.assign(currentConfig.modules, DEFAULT_MODULE_STATE); currentConfig.cspRules = DEFAULT_CSP_RULES_TEMPLATE.map(rule => ({ ...rule })); Whitelisting.clearAllWhitelists(); ProcessedElementsCache.clear(); CSPModule.removeCSP(); StorageManager.saveConfig(); location.reload(); } } }; function initializeAdBlocker() { UIController.init(); if (currentConfig.modules.manageCSP) { CSPModule.applyCSP(); } } if (document.readyState === 'loading') { initializeAdBlocker(); } else { setTimeout(initializeAdBlocker, 0); } })();