${title}
www.example.com仅匹配指定子域名 (推荐)*example.com匹配主域名及其所有子域名https://www.youtube.com/watch*匹配特定开头的路径re:[^/]+\\.example\\.com/path/使用正则表达式部分网站跳转外链的时候会跳转到一个确认网页,配置参数会把对应参数内的外链直接转换为可点击链接。
// ==UserScript== // @name URLCleaner - 通用链接净化 // @namespace You Boy // @version 1.2 // @description 自动净化链接,移除烦人的追踪参数,让您的网络足迹更干净、隐私更安全。性能至上,静默运行,对网页零侵入。支持灵活的自定义规则,是您掌控链接、保护隐私的终极利器。 // @author You Boy // @match *://*/* // @grant GM_addStyle // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_addValueChangeListener // @grant unsafeWindow // @run-at document-start // @license MIT // @downloadURL none // ==/UserScript== (function () { 'use strict'; // 是否开启调试模式 const IS_DEBUG = false; if (window.self !== window.top) { if (IS_DEBUG) { console.log( '%cURLCleaner%c[Sandbox]%c Skipped in iframe: %s', 'background:#00a1d6;color:white;border-radius:3px;padding:2px 6px;', 'background:#7f8c8d;color:white;border-radius:3px;padding:1px 4px;font-size:0.8em;margin-left:4px;', 'color:grey;', window.location.href ); } return; } // --- 沙箱环境 --- const Sandbox = { DEFAULT_CONFIG: { general: { params: ['spm_id_from', 'from_source', 'utm_source'] }, rules: [] }, config: null, // 加载配置 loadConfig() { let config = GM_getValue('ulcConfig'); if (!config || typeof config.general === 'undefined' || typeof config.rules === 'undefined') { config = JSON.parse(JSON.stringify(this.DEFAULT_CONFIG)); } config.general = config.general || { params: [] }; config.rules = config.rules || []; config.rules.forEach(rule => { if (typeof rule.match === 'string') { rule.match = [rule.match]; } }); this.config = config; }, // 初始化事件和菜单命令 init() { // 监听来自注入代码的保存请求 window.addEventListener('ulc-save-config', (event) => { GM_setValue('ulcConfig', event.detail); }); // 注册油猴菜单 GM_registerMenuCommand('设置', () => { window.dispatchEvent(new CustomEvent('ulc-open-settings')); }); // 监听存储变化 GM_addValueChangeListener('ulcConfig', (name, old_value, new_value, remote) => { if (remote) { this.config = new_value; // 通知更新 window.dispatchEvent(new CustomEvent('ulc-config-updated', { detail: new_value })); } }); } }; const StyleInjector = { inject(PANEL_ID) { const containerID = `#${PANEL_ID}`; GM_addStyle(` ${containerID} { all: initial; display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 2147483647; width: 90vw; min-width: 600px; max-width: 800px; height: 500px; max-height: 80vh; background: #fff; border-radius: 8px; box-shadow: 0 8px 20px rgba(0,0,0,0.2); display: flex; flex-direction: row; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; color: #333; font-size: 14px; } ${containerID} *, ${containerID} *::before, ${containerID} *::after { box-sizing: border-box; margin: 0; padding: 0; border: 0; font: inherit; vertical-align: baseline; background: transparent; color: inherit; text-align: left; line-height: 1.5; } ${containerID} div, ${containerID} span, ${containerID} ul, ${containerID} li, ${containerID} label { all: unset; box-sizing: border-box; } ${containerID} h3 { all: unset; box-sizing: border-box; display: block; font-size: 16px; font-weight: 600; } ${containerID} button { all: unset; box-sizing: border-box; display: inline-block; text-align: center; cursor: pointer; border-radius: 4px; padding: 8px 15px; font-size: 14px; transition: background-color 0.2s, color 0.2s; line-height: 1; white-space: nowrap; } ${containerID} input, ${containerID} textarea { all: unset; box-sizing: border-box; display: block; width: 100%; border: 1px solid #ccc; border-radius: 4px; padding: 10px; font-size: 14px; margin-bottom: 15px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #fff; line-height: 1.4; } ${containerID} input[type="checkbox"] { all: unset; box-sizing: border-box; appearance: none; -webkit-appearance: none; display: inline-block; width: 16px; height: 16px; border: 1px solid #ccc; border-radius: 4px; margin-right: 8px; vertical-align: middle; position: relative; cursor: pointer; flex-shrink: 0; } ${containerID} textarea { min-height: 80px; resize: vertical; } ${containerID} textarea::placeholder { white-space: pre-wrap; word-wrap: break-word; } ${containerID} code { width: initial; height: initial; display: initial; font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace; } ${containerID} button.ulc-btn-primary { background-color: #00a1d6; color: #fff; padding-block: 12px; } ${containerID} button.ulc-btn-primary:hover { background-color: #00b5e5; } ${containerID} button.ulc-btn-secondary { background-color: #fff; color: #767676; border: 1px solid #e3e3e3; } ${containerID} button.ulc-btn-secondary:hover { background-color: #e0e0e0; } ${containerID} button.ulc-btn-danger { border: 1px solid #ff4d4d; color: #ff4d4d; } ${containerID} button.ulc-btn-danger:hover { background-color: #ff4d4d; color: white; } ${containerID} .ulc-sidebar { display:flex; width: 180px; border-right: 1px solid #eee; flex-shrink: 0; flex-direction: column; } ${containerID} .ulc-search-container { padding: 10px 15px 0; } ${containerID} #ulc-rule-search { all: unset; box-sizing: border-box; width: 100%; border: 1px solid #ddd; border-radius: 4px; padding: 6px 10px; font-size: 13px; background-color: #fff; } ${containerID} .ulc-tabs { display: block; list-style: none; padding: 13px 0 10px; flex-grow: 1; overflow-y: auto; } ${containerID} .ulc-tab { position: relative; display: flex; align-items: center; height: 40px; padding: 0 18px; cursor: pointer; contain: strict; content-visibility: auto; contain-intrinsic-size: auto 40px; min-width: 0; } ${containerID} .ulc-tab::before { content: ''; position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 3px; height: 50%; background-color: transparent; transition: background-color 0.2s; } ${containerID} .ulc-tab:hover { background: #f5f5f5; } ${containerID} .ulc-tab.active { font-weight: 600; color: #00a1d6; } ${containerID} .ulc-tab.active::before { background-color: #00a1d6; } ${containerID} .ulc-tab > span { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } ${containerID} #ulc-add-rule-btn { display: block; text-align: center; padding: 12px; cursor: pointer; background: #fafafa; border-top: 1px solid #eee; color: #333; font-size: 14px; flex-shrink: 0; } ${containerID} #ulc-add-rule-btn::after { content: ' 新增规则'; } ${containerID} #ulc-add-rule-btn:hover { background: #f0f0f0; } ${containerID} .ulc-main-content { display:flex; flex-grow: 1; flex-direction: column; overflow: hidden; } ${containerID} .ulc-header { display: flex; justify-content: space-between; align-items: center; padding: 8px 15px; min-height: 55px; border-bottom: 1px solid #eee; flex-shrink: 0; } ${containerID} .ulc-title-container { display: flex; align-items: center; flex-grow: 1; max-width: 80%; } ${containerID} .ulc-title-container > h3 { max-width: 80%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } ${containerID} .ulc-edit-icon { display: none; cursor: pointer; margin-left: 8px; width: 16px; height: 16px; vertical-align: middle; } ${containerID} .ulc-title-container:hover .ulc-edit-icon { display: inline-block; } ${containerID} #ulc-close-btn { font-size: 24px; cursor: pointer; color: #999; padding: 5px; line-height: 1; flex-shrink: 0; } ${containerID} #ulc-close-btn:hover { color: #333; } ${containerID} .ulc-sub-header { display: flex; align-items: flex-start; justify-content: flex-start; padding: 8px 15px; background: #f9f9f9; border-bottom: 1px solid #eee; font-size: 12px; color: #666; flex-shrink: 0; } ${containerID} .ulc-sub-header > span { display: inline; flex-shrink: 0; margin-right: 8px; line-height: 22px; } ${containerID} .ulc-match-tags { display: flex; flex-wrap: wrap; gap: 6px; max-height: 26px; overflow: hidden; transition: max-height 0.3s ease; flex-grow: 1; } ${containerID} .ulc-match-tags:hover { max-height: 200px; } ${containerID} .ulc-match-tags code { display: inline; background: #e9e9e9; color: #c7254e; padding: 2px 6px; border-radius: 4px; font-size: 12px; white-space: nowrap; } ${containerID} .ulc-add { display: flex; align-items: center; padding: 10px 15px; border-bottom: 1px solid #eee; flex-shrink: 0; } ${containerID} #ulc-new-param { margin-right: 10px; padding: 8px; margin-bottom: 0; } ${containerID} .ulc-list { display: flex; padding: 10px; overflow-y: auto; flex-grow: 1; flex-wrap: wrap; align-content: flex-start; } ${containerID} .ulc-list:empty::before { content: "未添加参数"; display: block; width: 100%; text-align: center; color: #999; font-size: 14px; padding: 20px; } ${containerID} .ulc-list-transform { position: relative; max-height: 100px; } ${containerID} .ulc-list-transform::before { content:"跳转参数"; display: inline-block; background: #FFF; position: absolute; top: -10px; left: 10px; padding: 0 5px; font-size: 12px; color: #999; } ${containerID} .ulc-list-transform .ulc-list-transform-content { display: flex; flex-wrap: wrap; gap: 8px; padding: 10px; border-top: 1px solid #eee; flex-shrink: 0; overflow-y: auto; height: 100%; } ${containerID} .ulc-list-transform .ulc-list-transform-content > span { display: inline-block; background: #fceeee; color: #333; padding: 3px 6px; border-radius: 3px; margin: 0; font-size: 14px; } ${containerID} .ulc-param { display: inline-flex; align-items: center; background: #eef0f2; color: #333; padding: 5px 10px; border-radius: 6px; margin: 5px; font-size: 14px; } ${containerID} .ulc-param span { display: inline; margin-right: 8px; } ${containerID} .ulc-delete { color: #999; cursor: pointer; font-weight: bold; font-size: 16px; line-height: 1; padding: 4px 8px; margin: -4px -8px; border-radius: 6px; } ${containerID} .ulc-delete:hover { color: #ff4d4d; } ${containerID} .ulc-rule-settings-footer { display: flex; justify-content: space-between; align-items: center; padding: 15px; border-top: 1px solid #eee; font-size: 13px; color: #555; flex-shrink: 0; } ${containerID} .ulc-rule-settings-footer label { display: flex; align-items: center; cursor: pointer; } ${containerID} .ulc-rule-settings-footer input[type="checkbox"]:checked { background-color: #00a1d6; border-color: #00a1d6; } ${containerID} .ulc-rule-settings-footer input[type="checkbox"]:checked::after { all: unset; box-sizing: border-box; content: ''; display: block; width: 5px; height: 9px; border: solid white; border-width: 0 2px 2px 0; transform: rotate(45deg); position: absolute; left: 5px; top: 2px; } ${containerID} .ulc-rule-settings-footer #ulc-config-text-btn { border-style: dashed; } ${containerID} .ulc-form-content { display: block; padding: 8px; flex-grow: 1; overflow-y: auto; } ${containerID} .ulc-form-content label { display: block; margin-bottom: 8px; font-weight: 500; margin-top: 3em; } ${containerID} .ulc-form-content label:first-child { margin-top: 0; } ${containerID} .ulc-form-content p { font-size: 12px; display: block; color: #999; } ${containerID} .ulc-form-actions { display: flex; padding: 15px; border-top: 1px solid #eee; justify-content: flex-end; gap: 10px; flex-shrink: 0; } ${containerID} .ulc-form-hint { display: block; font-size: 12px; color: #666; margin-top: -5px; margin-bottom: 15px; } ${containerID} .ulc-hint-title { display: block; font-weight: bold; margin-top: 8px; } ${containerID} .ulc-hint-line { display: flex; align-items: center; margin-top: 4px; } ${containerID} .ulc-hint-line code { display: inline-block; flex-shrink: 0; background: #f5f5f5; color: #c7254e; padding: 2px 6px; border-radius: 4px; font-size: 12px; } ${containerID} .ulc-hint-line span { display: inline; margin-left: 8px; } ${containerID} #ulc-config-textarea { height: 100%; min-height: 100px; resize: vertical; margin-bottom: 0; } ${containerID} #ulc-toast { all: initial; box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; position: absolute; top: 60px; left: calc( 50% + 90px ); transform: translateX(-50%); background-color: rgba(0, 0, 0, 0.75); color: white; padding: 10px 20px; border-radius: 20px; font-size: 14px; z-index: 10; opacity: 0; visibility: hidden; transition: opacity 0.3s, visibility 0.3s; white-space: pre-wrap; line-height: 1.4; display: inline-block; max-width: 560px; } ${containerID} #ulc-toast.show { opacity: 1; visibility: visible; } ${containerID} .ulc-confirming-action { background-color: #ff4d4d !important; border-color: #ff4d4d !important; color: white !important; } ${containerID} .ulc-confirming-action:hover { background-color: #e60000 !important; } ${containerID} .ulc-confirming-action, ${containerID} .ulc-confirmation-activating { position: relative; } ${containerID} .ulc-confirming-action:hover::before, ${containerID} .ulc-confirming-action:focus::before { content: attr(data-confirm-desc); position: absolute; bottom: 100%; right: 0; margin-bottom: 8px; background: #333; color: white; padding: 8px 12px; border-radius: 4px; font-size: 13px; z-index: 1; pointer-events: none; max-width: 300px; min-width: 220px; white-space: normal; text-align: left; line-height: 1.4; } ${containerID} .ulc-confirming-action:hover::after, ${containerID} .ulc-confirming-action:focus::after { content: ''; position: absolute; bottom: 100%; right: 50%; transform: translateX(-50%); margin-bottom: -4px; border: 6px solid transparent; border-top-color: #333; z-index: 1; pointer-events: none; } ${containerID} .ulc-confirmation-activating { cursor: wait; animation: ulc-pulse 0.5s ease-out; } @keyframes ulc-pulse { 0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 77, 77, 0.7); } 50% { transform: scale(1.02); box-shadow: 0 0 0 8px rgba(255, 77, 77, 0); } 100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 77, 77, 0); } } @media (max-width: 600px) { ${containerID} { width: 100vw; height: 100vh; max-height: 100vh; min-width: 0; border-radius: 0; flex-direction: column; } ${containerID} .ulc-sidebar { width: 100%; height: auto; flex-direction: row; flex-wrap: wrap; align-items: center; border-right: 0; border-bottom: 1px solid #eee; flex-shrink: 0; padding: 12px 12px 0; gap: 10px; } ${containerID} .ulc-search-container { order: 1; flex-grow: 1; padding: 0; } ${containerID} #ulc-rule-search { font-size: 15px; padding: 10px 12px; } ${containerID} #ulc-add-rule-btn { order: 2; flex-shrink: 0; padding: 0; margin: 0; border: 1px solid #ddd; font-size: 0; line-height: 1; background: #fff; position: relative; display: flex; justify-content: center; align-items: center; height: 39px; width: 39px; } ${containerID} #ulc-add-rule-btn::after { font-size: 20px; content: '+'; } ${containerID} .ulc-tabs { order: 3; flex-basis: 100%; height: auto; display: flex; flex-direction: row; overflow-x: auto; white-space: nowrap; padding: 0; margin-top: 10px; border-top: 1px solid #f0f0f0; } ${containerID} .ulc-tab { display: flex; justify-content: center; align-items: center; width: 90px; height: 40px; padding: 0 10px; border-left: 0; border-bottom: 3px solid transparent; font-size: 15px; flex-shrink: 0; contain: strict; content-visibility: auto; contain-intrinsic-size: 90px 40px; min-width: 0; } ${containerID} .ulc-tab::before { display: none; } ${containerID} .ulc-tab.active { border-bottom-color: #00a1d6; color: #00a1d6; background-color: transparent; } ${containerID} .ulc-param { padding: 8px 12px; font-size: 15px; } ${containerID} .ulc-delete { padding: 8px; } ${containerID} .ulc-edit-icon { display:inline-block; } ${containerID} #ulc-toast { left: 50%; } } `); } }; const CodeInjector = { injectedCode: function (sandboxConfig, sandboxDefaultConfig, { IS_DEBUG, PANEL_ID, isFallbackMode = false, sandboxUnsafeWindow }) { (() => { // 发送“心跳”信号 window.dispatchEvent(new CustomEvent('ulc-injection-success')); const GENERAL_TAB_ID = 'general'; const Logger = { _styles: { brand: 'background: #00a1d6; color: white; border-radius: 3px; padding: 2px 6px;', tagBase: 'color: white; border-radius: 3px; padding: 1px 5px; font-size: 0.8em; margin-left: 4px;', get INFO() { return `background: #3498db; ${this.tagBase}`; }, get WARN() { return `background: #f39c12; ${this.tagBase}`; }, get ERROR() { return `background: #e74c3c; ${this.tagBase}`; }, get GROUP() { return `background: #95a5a6; ${this.tagBase}`; }, // 新增GROUP样式 title: 'font-weight: bold;', }, _createLog(type, isGrouped, ...args) { if (!IS_DEBUG) return; const brand = '%cURLCleaner'; const tag = `%c${type.toUpperCase()}`; const brandStyle = this._styles.brand; const tagStyle = this._styles[type]; if (!isGrouped) { console.log(brand + tag, brandStyle, tagStyle, ...args); } else { const [title, ...content] = args; const titleStyle = `${this._styles.title} color: ${tagStyle.match(/background: (#\w+);/)[1] || 'inherit'};`; console.groupCollapsed(brand + tag + `%c ${title}`, brandStyle, tagStyle, titleStyle); if (content.length > 0) { const consoleMethod = type === 'INFO' ? 'log' : type.toLowerCase(); content.forEach(item => console[consoleMethod](item)); } console.groupEnd(); } }, log(...args) { this._createLog('INFO', false, ...args); }, warn(title, ...content) { this._createLog('WARN', true, title, ...content); }, error(title, ...content) { this._createLog('ERROR', true, title, ...content); }, group(title) { if (IS_DEBUG) { console.groupCollapsed( `%cURLCleaner%cGROUP%c ${title}`, this._styles.brand, this._styles.GROUP, this._styles.title ); } }, groupEnd() { if (IS_DEBUG) { console.groupEnd(); } }, info(...args) { if (IS_DEBUG) { console.log(...args); } } }; if (isFallbackMode) { Logger.log('Fallback mode activated due to CSP.'); } else { Logger.log('Script injected and running in standard mode.'); } // --- Utils (工具函数) --- const Utils = { debounce(func, delay = 250) { let timeoutId; return function (...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; }, // 字符串转为正则表达式对象 wildcardToRegex(pattern) { try { if (pattern.startsWith('re:')) { return new RegExp(pattern.substring(3)); } let protocol = '*'; let host = pattern; let path = '/*'; if (host.includes('://')) { const parts = host.split('://'); protocol = parts[0]; host = parts[1]; } if (host.includes('/')) { const hostParts = host.split('/'); host = hostParts.shift(); path = '/' + hostParts.join('/'); if (!path.endsWith('*')) { path += '*'; } } const protocolRegex = protocol.replace(/\*/g, 'https?'); const hostRegex = host.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*'); const pathRegex = path.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*'); const finalRegexString = `^${protocolRegex}://${hostRegex}${pathRegex}$`; return new RegExp(finalRegexString); } catch (e) { Logger.warn(`Invalid regex pattern provided, falling back to non-matching pattern.`, { pattern, error: e.message }); return new RegExp('$.'); } }, // 严格检查是否是有效的URL isValidAbsoluteURL(str) { if (typeof str !== 'string' || str.trim() === '') return false; try { const url = new URL(str); return ['http:', 'https:', 'ftp:', 'ftps:'].includes(url.protocol); } catch (e) { return false; } }, // 宽松地尝试解析URL tryParseURL(str) { if (typeof str !== 'string' || str.trim() === '') return null; try { if (str.includes('://') || str.startsWith('/') || str.startsWith('?') || str.startsWith('#')) { return new URL(str, window.location.href); } return null; } catch (e) { return null; } }, // 尝试所有解码方式 tryAllDecodes(value) { if (!value) return null; // 解码函数 const decoders = [ (val) => atob(val), (val) => decodeURIComponent(val), (val) => decodeURIComponent(decodeURIComponent(val)), ]; const applyDecoders = (input) => { if (Utils.isValidAbsoluteURL(input)) return input; for (const decoder of decoders) { try { const decoded = decoder(input); if (decoded && Utils.isValidAbsoluteURL(decoded)) { return decoded; } } catch (error) { /* Silently ignore decoding errors */ } } return null; }; const variants = [ value, // 原始值 value.split('').reverse().join(''), // 反转字符串 ]; for (const variant of variants) { const decoded = applyDecoders(variant); if (decoded) return decoded; } return null; }, // 从奇怪的参数中提取URL extractUrlFromWeirdParam(input) { try { const url = input instanceof URL ? input : new URL(input); const [key] = url.searchParams.entries().next().value || []; if (url.searchParams.size === 1 && key && !url.searchParams.get(key)) { const decoded = Utils.tryAllDecodes(key); if (decoded) return decoded; } } catch (_) { /* Silently ignore parsing errors */ } return null; }, // 生成规则的唯一ID getRuleTabId(ruleOrName) { if (typeof ruleOrName === 'string' && ruleOrName === GENERAL_TAB_ID) { return GENERAL_TAB_ID; } const name = (typeof ruleOrName === 'object' && ruleOrName.name) ? ruleOrName.name : ruleOrName; if (name === GENERAL_TAB_ID || typeof name !== 'string' || name.trim() === '') { return GENERAL_TAB_ID; } try { const utf8Name = unescape(encodeURIComponent(name)); return `rule-${btoa(utf8Name)}`; } catch (e) { Logger.error(`Failed to generate ID for rule name: ${name}`, e); return `rule-error-${Date.now()}`; } }, isValidHttpLink(linkElement) { if (!linkElement || linkElement.tagName !== 'A') return false; const hrefAttr = linkElement.getAttribute('href'); if (!hrefAttr || hrefAttr.trim().startsWith('#') || hrefAttr.trim().startsWith('javascript:')) return false; try { const url = new URL(linkElement.href); return ['http:', 'https:'].includes(url.protocol); } catch (error) { return false; } }, randomString() { const length = Math.floor(Math.random() * 7) + 6; let result = ''; while (result.length < length) result += Math.random().toString(36).substring(2); result = result.substring(0, length); if (/^[0-9]/.test(result)) result = 'p' + result.substring(1); return result; }, // 验证配置文件合法性 validateConfigObject(config) { if (typeof config !== 'object' || config === null) return "配置必须是一个对象。"; if (typeof config.general !== 'object' || config.general === null) return `配置缺少 '${GENERAL_TAB_ID}' 对象。`; if (!Array.isArray(config.general.params)) return "'general.params' 必须是一个数组。"; if (config.general.params.some(p => typeof p !== 'string')) return "'general.params' 数组中包含了非字符串元素。"; if (!Array.isArray(config.rules)) return "配置缺少 'rules' 数组。"; const ruleNames = new Set(); for (let i = 0; i < config.rules.length; i++) { const rule = config.rules[i]; if (typeof rule !== 'object' || rule === null) return `规则 #${i + 1} 不是一个有效的对象。`; if (typeof rule.name !== 'string' || !rule.name.trim()) return `规则 #${i + 1} 缺少有效的 'name' 属性。`; // 检查规则名称是否重复 const ruleName = rule.name.trim().toLowerCase(); if (ruleNames.has(ruleName)) { return `配置中存在重复的规则名称: "${rule.name}"`; } ruleNames.add(ruleName); if (typeof rule.match === 'string') { rule.match = [rule.match]; } if (!Array.isArray(rule.match) || rule.match.length === 0) return `规则 "${rule.name}" 缺少有效的 'match' 数组。`; if (rule.match.some(m => typeof m !== 'string' || !m.trim())) return `规则 "${rule.name}" 的 'match' 数组中包含无效或空元素。`; if (rule.params && !Array.isArray(rule.params)) return `规则 "${rule.name}" 的 'params' 必须是数组。`; if (rule.params && rule.params.some(p => typeof p !== 'string')) return `规则 "${rule.name}" 的 'params' 数组中包含非字符串元素。`; if (rule.transform && !Array.isArray(rule.transform)) return `规则 "${rule.name}" 的 'transform' 必须是数组。`; if (rule.transform && rule.transform.some(t => typeof t !== 'string')) return `规则 "${rule.name}" 的 'transform' 数组中包含非字符串元素。`; } return null; }, }; // --- State (状态管理) --- const State = { config: null, DEFAULT_CONFIG: null, paramsToRemove: new Set(), transformKeysToUse: new Set(), cleanedAttrName: '', invalidAttrName: '', ui: { activeTab: GENERAL_TAB_ID, activeRuleIndex: -1, view: 'list', // 'list', 'add', 'edit', 'config-text' searchQuery: '', ACTIVATION_DELAY: 800, // confirmation activation delay }, dom: { settingsPanel: null, sidebarContainer: null, mainContentContainer: null, panelId: PANEL_ID, }, toastTimer: null, init(config, defaultConfig) { this.config = config; this.DEFAULT_CONFIG = defaultConfig; }, }; // --- Core (核心净化与转换逻辑) --- const Core = { saveConfig() { window.dispatchEvent(new CustomEvent('ulc-save-config', { detail: State.config })); this.setActiveParameters(); }, setActiveParameters() { const matchingRules = []; for (const rule of State.config.rules) { for (const match of rule.match) { if (Utils.wildcardToRegex(match).test(window.location.href)) { matchingRules.push(rule); break; } } } const params = new Set(); const transforms = new Set(); if (matchingRules.length > 0) { let shouldApplyGeneral = false; matchingRules.forEach(rule => { (rule.params || []).forEach(p => params.add(p)); if (Array.isArray(rule.transform)) { rule.transform.forEach(t => transforms.add(t)); } if (rule.applyGeneral) { shouldApplyGeneral = true; } }); if (shouldApplyGeneral) { (State.config.general.params || []).forEach(p => params.add(p)); } } else { (State.config.general.params || []).forEach(p => params.add(p)); } State.paramsToRemove = params; State.transformKeysToUse = transforms; Logger.group('Active Parameters Updated', true); Logger.info('URL:', window.location.href); Logger.info('Matching rules found:', matchingRules.map(r => r.name)); Logger.info('Params to remove:', [...State.paramsToRemove]); Logger.info('Transform keys to use:', [...State.transformKeysToUse]); Logger.groupEnd(); }, cleanUrl(urlString, recursionDepth = 0) { // 增加熔断机制防止无限递归 const MAX_RECURSION_DEPTH = 3; if (recursionDepth > MAX_RECURSION_DEPTH) { return urlString; } if (!urlString || typeof urlString !== 'string') return urlString; const originalUrlString = urlString; const isOriginalRelative = !/^(https?:)?\/\//.test(originalUrlString); let currentUrl; try { currentUrl = new URL(originalUrlString, window.location.href); } catch (e) { return originalUrlString; } // --- 1:链接转换 --- if (State.transformKeysToUse.size > 0) { if (currentUrl.searchParams.size === 1) { const weirdUrl = Utils.extractUrlFromWeirdParam(currentUrl.href); if (weirdUrl) return weirdUrl; } for (const key of currentUrl.searchParams.keys()) { if (State.transformKeysToUse.has(key)) { const value = currentUrl.searchParams.get(key); const transformedUrl = Utils.tryAllDecodes(value); if (transformedUrl) { return this.cleanUrl(transformedUrl, recursionDepth + 1); } } } } // --- 2:参数净化 --- const finalUrlObject = new URL(currentUrl); let modified = false; // 创建一个临时的Set来检查,避免重复遍历 const paramsToCheck = new Set(finalUrlObject.searchParams.keys()); if (paramsToCheck.size > 0) { for (const param of State.paramsToRemove) { if (paramsToCheck.has(param)) { finalUrlObject.searchParams.delete(param); modified = true; } } } if (!modified) return originalUrlString; if (isOriginalRelative) { return finalUrlObject.pathname + finalUrlObject.search + finalUrlObject.hash; } else { return finalUrlObject.href; } }, }; // --- UI (界面渲染) --- const UI = { _policy: null, setSafelyInnerHTML(element, htmlString) { if (this._policy === null) { this._policy = false; if (window.trustedTypes && window.trustedTypes.createPolicy) { try { this._policy = window.trustedTypes.createPolicy('URLCleanerPolicy#html', { createHTML: s => s, }); } catch (e) { if (window.trustedTypes.defaultPolicy) { this._policy = window.trustedTypes.defaultPolicy; Logger.log('Using host page default Trusted Types policy as a fallback.'); } } } } if (this._policy) { try { element.innerHTML = this._policy.createHTML(htmlString); } catch (e) { Logger.error('UI Rendering failed even with a Trusted Types policy.', `Policy in use: ${this._policy.name}`, `Error: ${e.message}`); } } else { try { element.innerHTML = htmlString; } catch (e) { Logger.error('UI Rendering blocked by CSP.', `Error: ${e.message}`); } } }, showToast(message, duration = 2000) { const toast = document.getElementById('ulc-toast'); if (!toast) return; toast.textContent = message; toast.classList.add('show'); if (State.toastTimer) clearTimeout(State.toastTimer); State.toastTimer = setTimeout(() => { toast.classList.remove('show'); State.toastTimer = null; }, duration); }, createSettingsPanel() { if (State.dom.settingsPanel) return; const panel = document.createElement('div'); panel.id = State.dom.panelId; this.setSafelyInnerHTML(panel, `
`); document.body.appendChild(panel); State.dom.settingsPanel = panel; State.dom.sidebarContainer = panel.querySelector('.ulc-sidebar'); State.dom.mainContentContainer = panel.querySelector('.ulc-main-content'); panel.addEventListener('click', Events.handlePanelClick); panel.addEventListener('keydown', e => { if (e.key === 'Enter' && e.target.id === 'ulc-new-param') Events.addParamsFromInput(); }); }, renderPanel() { if (!State.dom.settingsPanel) return; this.renderSidebar(); this.renderMainContent(); const input = document.getElementById('ulc-new-param') || document.getElementById('ulc-rule-name'); if (input) input.focus(); }, updateRuleList() { const tabsContainer = State.dom.sidebarContainer.querySelector('.ulc-tabs'); if (!tabsContainer) return; const searchQuery = (State.ui.searchQuery || '').toLowerCase(); const fragment = document.createDocumentFragment(); const generalTab = document.createElement('li'); generalTab.className = 'ulc-tab'; generalTab.dataset.tabId = GENERAL_TAB_ID; generalTab.dataset.ruleIndex = '-1'; generalTab.textContent = '通用规则'; if (State.ui.activeTab === GENERAL_TAB_ID) { generalTab.classList.add('active'); } fragment.appendChild(generalTab); State.config.rules.forEach((rule, index) => { const li = document.createElement('li'); li.className = 'ulc-tab'; li.dataset.tabId = Utils.getRuleTabId(rule); li.dataset.ruleIndex = index.toString(); li.title = `${rule.name}\n${rule.match.join('\n')}`; const textSpan = document.createElement('span'); textSpan.textContent = rule.name; li.appendChild(textSpan); const isVisible = searchQuery ? rule.name.toLowerCase().includes(searchQuery) : true; if (!isVisible) { li.style.display = 'none'; } if (State.ui.activeTab === Utils.getRuleTabId(rule)) { li.classList.add('active'); } fragment.appendChild(li); }); this.setSafelyInnerHTML(tabsContainer, '') tabsContainer.appendChild(fragment); const activeTabEl = tabsContainer.querySelector('.ulc-tab.active'); if (activeTabEl) { requestAnimationFrame(() => activeTabEl.scrollIntoView({ block: 'nearest', behavior: 'auto' })); } }, renderSidebar() { if (!State.dom.sidebarContainer) return; const sidebarHtml = `www.example.com仅匹配指定子域名 (推荐)*example.com匹配主域名及其所有子域名https://www.youtube.com/watch*匹配特定开头的路径re:[^/]+\\.example\\.com/path/使用正则表达式部分网站跳转外链的时候会跳转到一个确认网页,配置参数会把对应参数内的外链直接转换为可点击链接。