// ==UserScript== // @name CSDN 文章页净化 // @namespace csdn-article-clean // @version 1.0.0 // @description 去广告、免登录复制(含去除复制尾巴)、自动展开全文与代码块、拦登录跳转、URL 去参。全部带开关。 // @tag CSDN 页面美化 // @author deran // @license MIT // @match *://*.blog.csdn.net/*/article/details/* // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant unsafeWindow // @run-at document-start // @noframes // ==/UserScript== (() => { 'use strict'; /* 沙箱里也要拿到页面真实的 window / csdn 对象 */ const page = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; /* ================================================================== 0. 配置 ================================================================== */ const CONFIG_KEY = 'cac_config'; const DEFAULTS = { cleanUrl: true, // URL 去追踪参数 ads: true, // 广告与推广位 loginGuard: true, // 拦截自动跳转登录页 unlockCopy: true, // 免登录复制 + 去掉复制尾巴 unlockContent: true, // 解锁全文与代码块高度 codeBlock: true, // 代码块复制按钮 + 不限高 hideToolbar: false, // 隐藏顶部导航 centerLayout: false, // 隐藏右栏、正文居中 }; const LABELS = { cleanUrl: 'URL 去追踪参数', ads: '广告与推广', loginGuard: '拦截自动跳登录页', unlockCopy: '免登录复制 / 去复制尾巴', unlockContent: '解锁全文与代码块高度', codeBlock: '代码块复制按钮', hideToolbar: '隐藏顶部导航', centerLayout: '正文居中(隐藏右栏)', }; const hasGM = typeof GM_getValue === 'function'; function readRaw(key, fallback) { try { return hasGM ? GM_getValue(key, fallback) : (localStorage.getItem(key) ?? fallback); } catch { return fallback; } } function writeRaw(key, value) { try { if (hasGM && typeof GM_setValue === 'function') GM_setValue(key, value); else localStorage.setItem(key, value); } catch { /* 存储不可用时只用内存配置 */ } } const config = (() => { try { return { ...DEFAULTS, ...JSON.parse(readRaw(CONFIG_KEY, '{}')) }; } catch { return { ...DEFAULTS }; } })(); function saveConfig() { writeRaw(CONFIG_KEY, JSON.stringify(config)); } /* ================================================================== 1. URL 去参 文章页的规范地址就是 /{user}/article/details/{id}, 分享链接里的 spm / utm_* / ops_request_misc 全是追踪位。 ================================================================== */ function cleanUrl() { const url = new URL(location.href); if (!url.search) return; /* 保留 hash(#comments 之类是真实锚点) */ const cleaned = url.origin + url.pathname + url.hash; if (cleaned !== location.href) { history.replaceState(history.state, '', cleaned); } } if (config.cleanUrl) { cleanUrl(); /* CSDN 文章页基本是整页导航,但仍接管一次以防站内 SPA 跳转 */ for (const method of ['pushState', 'replaceState']) { const original = history[method]; history[method] = function (...args) { const result = original.apply(this, args); if (config.cleanUrl) cleanUrl(); return result; }; } } /* ================================================================== 2. 样式 CSS 组按开关拼装,改开关只重建这一个