// ==UserScript== // @name CSDN优化增强 // @namespace http://tampermonkey.net/ // @version 2026.11.20 // @description CSDN功能增强:查看原始LaTeX、查看原图、自动跳转等 // @author AN drew // @match https://*.csdn.net/* // @noframes // @require https://lib.baomitu.com/jquery/3.5.0/jquery.min.js // @grant GM_addStyle // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // ==/UserScript== (function() { 'use strict'; // 全局配置 // checkInterval: Utils.waitForElement 的轮询间隔(毫秒) // maxRetries: Utils.waitForElement 的最大轮询次数,与 checkInterval 共同决定最长等待时间 // copyOnImageClick: 是否接管图片公式的点击复制;复制使用页面级 textarea + execCommand,不经过扩展 API // observerConfig: 图片查看器容器的 MutationObserver 监听项 // childList: 监听子节点增删,用于发现预览容器 // subtree: 同时监听所有后代节点 // attributes: 不监听属性变化,避免 Swiper class 切换带来的额外回调 // characterData: 不监听文本内容变化 const CONFIG = { checkInterval: 500, maxRetries: 20, copyOnImageClick: true, observerConfig: { childList: true, subtree: true, attributes: false, characterData: false } }; // 共享状态:SPA 地址观察器与初始化标记 let urlObserver = null; let lastUrl = location.href; let initialized = false; // CSS样式(提前加载) GM_addStyle(` /* 基础调整 */ .edit-drawer-box.el_mcm-drawer.rtl.open, .edit_Drawer_btn, .transparent-modal, .csdn-side-toolbar, .recommend-box, #copyright-box, .toolbar-advert, .simple-moyan-member-wrap{ display: none !important; } .cke_dialog_container::-webkit-scrollbar { width: 0 !important } /*底部广告*/ #dmp_ad_58{ display: none !important; } /*两侧广告*/ .simple-ad-slot, .article-aside-container + .simple-ad-slot-right{ display: none !important; } /*右上角气泡广告*/ #csdn-new-user-gift-bubble{ display: none !important; } /*本文章已经生成可运行项目*/ .runner-box{ display: none !important; } /*首页轮播广告*/ .kp_bos_swiper{ display: none !important; } /*流量券提示*/ .csdn-toolbar-creative-mp{ display: none !important; } /*会员中心*/ .toolbar-btn-vip{ display: none !important; } /*精品课程*/ .member.slide-box{ display: none !important; } /*GPU算力*/ .layout-sidebar .layout-menus .layout-menus—main-group:nth-of-type(2) .layout-menus—main .layout-menus—main_item:first-child{ display: none !important; } .layout-sidebar .layout-menus .layout-menus—main-group:nth-of-type(3) .layout-menus—main .layout-menus—main_item:last-child{ display: none !important; } /* 隐藏两个侧边栏 */ .blog_container_aside, #rightAside { display: none !important; } /* 基础调整 */ .container { width: 100% !important; max-width: 100% !important; margin: 0 auto !important; padding: 0 !important; } /* 主内容区调整 */ main { float: none !important; width: 100% !important; margin: 0 auto 40px auto !important; padding: 0 20px !important; box-sizing: border-box !important; } /* 内容区容器调整 */ @media (min-width: 1600px) { html body.has-simple-ad-background-skin .simple-column-page.has-ad-slots #mainBox{ left: auto !important; } } html body .simple-column-page #mainBox .article-aside-container .sidebar{ left: auto !important; } /* 博客内容容器调整 */ main div.blog-content-box { width: 100% !important; max-width: 100% !important; margin: 0 auto !important; padding: 0 24px !important; box-sizing: border-box !important; } /*推荐文章卡片*/ .simple-blue-card { display: none !important; } /*图片翻页按钮*/ .swiper-button-lock { display: block !important; } .imgViewDom .swiper .swiper-button-prev::after, .imgViewDom .swiper .swiper-button-next::after { display: none !important; } /* 响应式断点调整 */ @media screen and (max-width: 1199px) { .nodata .container { padding: 0 20px !important; } .nodata .container main { width: 100% !important; max-width: 900px !important; margin: 0 auto 40px auto !important; padding: 0 !important; } main div.blog-content-box { padding: 0 20px !important; } .more-toolbox-new.more-toolbar > .left-toolbox, .more-toolbox-new.more-toolbar.more-toolbox-active > .left-toolbox { width: 900px !important; left: 50% !important; transform: translateX(-50%) !important; } } @media (min-width: 1200px) and (max-width: 1319px) { .nodata .container { padding: 0 30px !important; } .nodata .container main { width: 100% !important; max-width: 1100px !important; margin: 0 auto 40px auto !important; padding: 0 !important; } main div.blog-content-box { padding: 0 24px !important; } .more-toolbox-new.more-toolbar > .left-toolbox, .more-toolbox-new.more-toolbar.more-toolbox-active > .left-toolbox { width: 1100px !important; left: 50% !important; transform: translateX(-50%) !important; } } @media (min-width: 1320px) and (max-width: 1439px) { .nodata .container { padding: 0 40px !important; } .nodata .container main { width: 100% !important; max-width: 1200px !important; margin: 0 auto 40px auto !important; padding: 0 !important; } main div.blog-content-box { padding: 0 24px !important; } .more-toolbox-new.more-toolbar > .left-toolbox, .more-toolbox-new.more-toolbar.more-toolbox-active > .left-toolbox { width: 1200px !important; left: 50% !important; transform: translateX(-50%) !important; } } @media (min-width: 1440px) and (max-width: 1549px) { .nodata .container { padding: 0 50px !important; } .nodata .container main { width: 100% !important; max-width: 1300px !important; margin: 0 auto 40px auto !important; padding: 0 !important; } main div.blog-content-box { padding: 0 24px !important; } .more-toolbox-new.more-toolbar > .left-toolbox, .more-toolbox-new.more-toolbar.more-toolbox-active > .left-toolbox { width: 1300px !important; left: 50% !important; transform: translateX(-50%) !important; } } @media (min-width: 1550px) and (max-width: 1699px) { .nodata .container { padding: 0 60px !important; } .nodata .container main { width: 100% !important; max-width: 1400px !important; margin: 0 auto 40px auto !important; padding: 0 !important; } main div.blog-content-box { padding: 0 24px !important; } .more-toolbox-new.more-toolbar > .left-toolbox, .more-toolbox-new.more-toolbar.more-toolbox-active > .left-toolbox { width: 1400px !important; left: 50% !important; transform: translateX(-50%) !important; } } @media screen and (min-width: 1700px) { .nodata .container { padding: 0 80px !important; } .nodata .container main { width: 100% !important; max-width: 1500px !important; margin: 0 auto 40px auto !important; padding: 0 !important; } main div.blog-content-box { padding: 0 24px !important; } .more-toolbox-new.more-toolbar > .left-toolbox, .more-toolbox-new.more-toolbar.more-toolbox-active > .left-toolbox { width: 1500px !important; left: 50% !important; transform: translateX(-50%) !important; } } /* 博客内容调整 */ main div.blog-content-box article { width: 100% !important; } main .article-header-box { width: 100% !important; max-width: 100% !important; } main div.blog-content-box pre { max-width: 100% !important; box-sizing: border-box !important; } main div.blog-content-box article .table-box { overflow-x: auto !important; } .comment-box.comment-box-new2 { width: 100% !important; max-width: 100% !important; box-sizing: border-box !important; } /*打印时隐藏水印*/ @media print { .print_watermark, .print_watermark_info { display: none !important; } } #article_content { padding-bottom: 70px; } /* LaTeX 原文显示模式 */ .wb-latex-raw{ display:inline; font-family:Consolas,Monaco,"Courier New",monospace; font-size:.95em; color:#0b4f9c; background:#f3f8ff; border:1px dashed #8ab4f8; border-radius:4px; padding:1px 4px; margin:0 2px; white-space:pre-wrap; word-break:break-word; user-select:text; cursor:copy; } `); // 通用工具函数 const Utils = { // 等待元素出现的函数(替代setInterval) waitForElement(selector, callback, maxAttempts = CONFIG.maxRetries) { let attempts = 0; const check = () => { attempts++; const element = document.querySelector(selector); if (element) { callback(element); return true; } else if (attempts < maxAttempts) { setTimeout(check, CONFIG.checkInterval); } return false; }; return check(); }, // 防抖函数 debounce(func, wait) { let timeout; return function executedFunction(...args) { const later = () => { clearTimeout(timeout); func(...args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; }, // 安全执行函数 safeExec(fn, context = null) { try { return fn.call(context); } catch (error) { console.warn('脚本执行出错:', error); return null; } } }; // LaTeX 公共工具:复制、页面提示、图片源码提取,供 LatexProcessor / LatexRawRevealer 共用 const LatexUtils = { tipTimer: null, imgCache: new WeakMap(), // 复制入口:优先异步 Clipboard API,失败时用页面级 execCommand 降级; // onDone 在复制结束后收到 true/false,调用方据此决定是否弹提示 copyToClipboard(text, onDone) { const finish = (ok) => { if (typeof onDone === 'function') onDone(ok); }; if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { navigator.clipboard.writeText(text).then(() => { console.log('公式已复制:', text); finish(true); }).catch(() => this.legacyCopy(text, finish)); } else { this.legacyCopy(text, finish); } }, // 低版本 Chrome / 沙箱环境的降级方案:页面内 textarea + execCommand,不走扩展进程 legacyCopy(text, finish) { let ta = null; try { ta = document.createElement('textarea'); ta.value = text; ta.setAttribute('readonly', ''); ta.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0'; document.body.appendChild(ta); ta.select(); const ok = document.execCommand('copy'); console.log(ok ? '公式已复制:' : '复制失败:', text); finish(!!ok); } catch (e) { console.error('复制失败:', e); finish(false); } finally { if (ta && ta.parentNode) ta.parentNode.removeChild(ta); } }, // 复制 LaTeX 并根据结果显示提示;空文本直接跳过 copyWithTip(latex) { if (!latex) return; this.copyToClipboard(latex, (ok) => { this.showTip(ok ? '已复制 Latex 原始文本' : '复制失败'); }); }, // 页面中下部短提示:复用同一个节点,避免每次点击都创建 DOM showTip(msg) { let tip = document.getElementById('wb-latex-tip'); if (!tip) { tip = document.createElement('div'); tip.id = 'wb-latex-tip'; Object.assign(tip.style, { position: 'fixed', left: '50%', bottom: '16px', transform: 'translateX(-50%)', zIndex: '99999', background: 'rgba(17,24,39,.9)', color: '#fff', padding: '8px 14px', borderRadius: '6px', fontSize: '13px', pointerEvents: 'none', whiteSpace: 'nowrap', maxWidth: '90vw', overflow: 'hidden', textOverflow: 'ellipsis' }); document.body.appendChild(tip); } tip.textContent = msg; clearTimeout(this.tipTimer); this.tipTimer = setTimeout(() => tip.remove(), 1800); }, // 去掉零宽字符并 trim,避免不可见字符混进 LaTeX 源码 clean(text) { return String(text || '') .replace(/[\u200b\u2060\ufeff]/g, '') .trim(); }, // alt 里是否像 LaTeX(避免把普通图片说明当成公式) looksLikeTex(text) { return /\\[a-zA-Z]|\^\{|\_\{|\{[^}]*\\[a-zA-Z]/.test(text); }, // 从 latex.csdn.net/eq?... 之类的 URL 中取 TeX;注意 CSDN 的 '+' 是字面加号, // 因此用 decodeURIComponent 而不是 URLSearchParams(后者会把 '+' 变成空格) texFromUrl(url) { if (!url) return ''; let part = ''; const eqIndex = url.search(/(?:eq\?|equation\?)/i); if (eqIndex > -1) { part = url.slice(url.indexOf('?', eqIndex) + 1); } else { const m = url.match(/[?&](?:tex|latex|formula|text)=/i); if (m) part = url.slice(m.index + m[0].length); } if (!part) return ''; part = part.split('#')[0].split('&')[0]; try { part = decodeURIComponent(part); } catch (e) { /* 已是明文则忽略 */ } return this.clean(part); }, // 图片式:alt / data-tex / title → src 中的 eq? 参数 → data-original // 同一图片节点缓存结果,避免重复点击时反复解码长 URL extractFromImg(img) { if (this.imgCache.has(img)) return this.imgCache.get(img); let latex = ''; for (const key of ['alt', 'data-tex', 'title']) { const val = img.getAttribute(key); if (val && this.looksLikeTex(val)) { latex = this.clean(val); break; } } if (!latex) { latex = this.texFromUrl(img.src || img.getAttribute('src') || '') || this.texFromUrl(img.getAttribute('data-original') || img.getAttribute('data-src') || ''); } // 只缓存解析成功的结果,避免图片后续补上 alt/src 时读到旧的空值 if (latex) this.imgCache.set(img, latex); return latex; } }; // LaTeX公式处理模块:iframe 样式修正 + 图片公式点击复制 const LatexProcessor = { copyBound: false, iframePollStarted: false, boundIframes: new WeakSet(), init() { // 一次性设置iframe监听 this.setupIframeListener(); // 设置公式复制功能 this.setupFormulaCopy(); }, setupIframeListener() { // 每次页面生命周期只启动一次轮询;SPA 换页时由 urlObserver 重置该标记 if (this.iframePollStarted) return; this.iframePollStarted = true; // 同一个 iframe 实例只绑一次 load;新实例会被 WeakSet 判定后重新绑定 Utils.waitForElement('#cke_1_contents iframe', (iframe) => { if (this.boundIframes.has(iframe)) return; this.boundIframes.add(iframe); const processIframeContent = () => { try { const iframeDoc = iframe.contentDocument; if (!iframeDoc) return; // 处理数学公式图片 iframeDoc.querySelectorAll('img.mathcode').forEach(img => { img.style.margin = '0px'; }); // 处理blockquote iframeDoc.querySelectorAll('blockquote').forEach(blockquote => { blockquote.style.background = 'transparent'; }); } catch (error) { console.warn('处理iframe内容出错:', error); } }; // 初始处理 processIframeContent(); // 监听iframe加载 iframe.addEventListener('load', processIframeContent); }); }, setupFormulaCopy() { // 按配置决定是否接管图片点击;关闭时完全不注册监听 if (!CONFIG.copyOnImageClick) return; // document 点击委托全局只绑一次,避免 SPA 切文章后重复绑定 if (this.copyBound) return; this.copyBound = true; // 使用事件委托处理公式复制 document.addEventListener('click', (event) => { const target = event.target; if (!target || !target.matches) return; // 处理mathcode图片 if (target.matches('img.mathcode')) { LatexUtils.copyWithTip(LatexUtils.extractFromImg(target)); return; } // 处理swiper幻灯片中的latex图片 if (target.matches('.swiper-slide-active img')) { const src = target.src || ''; if (/latex|eq\?|equation\?/i.test(src)) { LatexUtils.copyWithTip(LatexUtils.texFromUrl(src)); } } }); } }; // LaTeX 原文显示模块(同时兼容 KaTeX 标签式 与 mathcode 图片式) // 菜单开启后:隐藏渲染结果,在其后插入可选的原始 LaTeX 文本;再次点击恢复 const LatexRawRevealer = { // 用普通 BMP 字符做勾选标记,不用 emoji,低版本 Chrome 也能正常显示 MENU_ON: '(✓) 显示 Latex 原始文本', MENU_OFF: '(×) 显示 Latex 原始文本', enabled: false, menuRegistered: false, menuId: null, canUpdateLabel: false, fallbackMenuRegistered: false, rawClass: 'wb-latex-raw', records: [], observer: null, done: new WeakSet(), init() { // SPA 切换文章时 initScript 会重跑,菜单只注册一次 if (!this.menuRegistered) { this.registerMenu(); this.menuRegistered = true; } // 若正处于原文模式,清理旧页面记录并重新扫描 if (this.enabled) { this.restoreAll(); this.applyAll(); } }, // 重新注册菜单以更新前缀标记;老版本 TM 没有 unregister 接口时退化为两个固定菜单 registerMenu() { if (typeof GM_registerMenuCommand !== 'function') return; this.canUpdateLabel = typeof GM_unregisterMenuCommand === 'function'; if (this.canUpdateLabel) { if (this.menuId != null) { try { GM_unregisterMenuCommand(this.menuId); } catch (e) { /* 忽略 */ } } this.menuId = GM_registerMenuCommand( this.enabled ? this.MENU_ON : this.MENU_OFF, () => this.toggle() ); } else if (!this.fallbackMenuRegistered) { GM_registerMenuCommand(this.MENU_ON, () => this.setEnabled(true)); GM_registerMenuCommand(this.MENU_OFF, () => this.setEnabled(false)); this.fallbackMenuRegistered = true; } }, // 菜单点击入口:取反当前状态并交给 setEnabled 统一处理 toggle() { this.setEnabled(!this.enabled); }, // 切换原文模式:先更新菜单标记,再决定应用还原还是重新扫描 setEnabled(next) { if (this.enabled === next) return; this.enabled = next; if (this.canUpdateLabel) this.registerMenu(); if (this.enabled) { this.applyAll(); this.startObserver(); LatexUtils.showTip('已开启:显示 LaTeX 原始文本(点击文本可复制)'); } else { this.restoreAll(); this.stopObserver(); LatexUtils.showTip('已关闭:恢复 LaTeX 公式渲染'); } }, // 标签式:优先 annotation,其次 MathML 文本兜底 extractFromKatex(el) { const ann = el.querySelector('annotation[encoding="application/x-tex"], annotation'); if (ann && ann.textContent.trim()) return LatexUtils.clean(ann.textContent); const mathml = el.querySelector('.katex-mathml'); if (!mathml) return ''; const text = LatexUtils.clean(mathml.textContent); // 在线页面常见:MathML 带缩进换行,最后一行就是 TeX const lines = text.split(/\r?\n/).map(s => s.trim()).filter(Boolean); if (lines.length > 1 && !/[<>]/.test(lines[lines.length - 1])) { return LatexUtils.clean(lines[lines.length - 1]); } // 二次保存的 HTML:MathML 标签被剥掉,只剩「可见字符 + TeX」拼接串 return this.guessFlattenedTex(text); }, // 对没有 annotation 的扁平文本做尽力还原(离线保存的 KaTeX 才会用到) guessFlattenedTex(text) { if (!text) return ''; // 没有反斜杠命令时:a1=20=1a_{1}=2^{0}=1 → 从 a_{1} 开始;nn / q=2q=2 → 取后一半 if (text.indexOf('\\') === -1) { const sub = text.search(/[_^]\{/); if (sub > 0) { let start = sub; const prevChar = text[start - 1]; if (/[A-Za-z]/.test(prevChar)) { while (start > 0 && /[A-Za-z]/.test(text[start - 1])) start--; } else if (/\d/.test(prevChar)) { while (start > 0 && /\d/.test(text[start - 1])) start--; } return LatexUtils.clean(text.slice(start)); } const half = Math.floor(text.length / 2); if (text.length % 2 === 0 && text.slice(0, half) === text.slice(half)) { return text.slice(half); } return text; } // 找到第一个 TeX 命令的起点:前面通常是 { 、空白 或 数学符号 for (let i = 0; i < text.length; i++) { if (text[i] !== '\\') continue; const prev = i > 0 ? text[i - 1] : ''; if (i === 0 || prev === '{' || /\s/.test(prev) || /[^\x00-\x7F]/.test(prev)) { const start = (prev === '{') ? i - 1 : i; return LatexUtils.clean(text.slice(start)); } } const brace = text.indexOf('{'); return brace > 0 ? LatexUtils.clean(text.slice(brace)) : text; }, // 扫描公式节点:隐藏渲染结果,在其后插入可复制的 LaTeX 文本 applyAll() { if (!this.enabled) return; const hosts = document.querySelectorAll( '.katex, img.mathcode, img[src*="latex"], img[data-original*="latex"]' ); hosts.forEach(el => { if (this.done.has(el)) return; const latex = el.classList.contains('katex') ? this.extractFromKatex(el) : LatexUtils.extractFromImg(el); if (!latex) return; this.done.add(el); const oldDisplay = el.style.display; el.style.setProperty('display', 'none', 'important'); const span = document.createElement('span'); span.className = this.rawClass; span.textContent = latex; span.title = '点击复制 LaTeX 原始文本'; span.addEventListener('click', (e) => { e.stopPropagation(); LatexUtils.copyWithTip(latex); }); if (el.parentNode) el.parentNode.insertBefore(span, el.nextSibling); this.records.push({ el, span, oldDisplay }); }); }, // 关闭原文模式:移除插入的 span,按记录恢复原节点的 display restoreAll() { this.records.forEach(({ el, span, oldDisplay }) => { if (span.parentNode) span.parentNode.removeChild(span); if (el.isConnected) el.style.display = oldDisplay; this.done.delete(el); }); this.records = []; document.querySelectorAll('.' + this.rawClass).forEach(n => n.remove()); }, // 仅在原文模式开启时监听新增节点;跳过自己插入的 span 以免自触发 startObserver() { if (this.observer) return; this.observer = new MutationObserver(Utils.debounce((mutations) => { let needRescan = false; for (const m of mutations) { if (m.target && m.target.closest && m.target.closest('.' + this.rawClass)) continue; (m.addedNodes || []).forEach(node => { if (node.nodeType === 1 && !node.classList.contains(this.rawClass)) { needRescan = true; } }); if (needRescan) break; } if (needRescan) this.applyAll(); }, 200)); // 只观察正文容器,避免灯箱等全屏弹层的 DOM 变动触发全页扫描 const root = document.querySelector('#article_content') || document.body; this.observer.observe(root, { childList: true, subtree: true }); }, // 停止动态观察并释放引用 stopObserver() { if (this.observer) { this.observer.disconnect(); this.observer = null; } } }; // 目录处理模块 // 默认收起文章目录侧栏 const CatalogProcessor = { pollStarted: false, // 等目录节点出现后点击收起按钮 init() { if (this.pollStarted) return; this.pollStarted = true; Utils.waitForElement('.catlog-guide-box', (catalogBox) => { if (!catalogBox.classList.contains('minisize')) { const hideBtn = catalogBox.querySelector('.btn-hide-catlog'); if (hideBtn) { hideBtn.click(); } } }); } }; // 链接跳转处理 // link.csdn.net 中转页读取目标地址后直接跳转 const LinkRedirector = { pollStarted: false, // 非中转页直接跳过;中转页读取加载提示中的 URL 后跳转 init() { if (this.pollStarted) return; this.pollStarted = true; if (!window.location.href.includes('link.csdn.net')) return; Utils.waitForElement('.loading-color2', (element) => { const url = element.textContent.trim(); if (url && url.startsWith('http')) { window.open(url, '_self'); } }); } }; // 图片查看器增强模块 // 在原图预览工具栏追加“查看原图”按钮 const ImageViewerEnhancer = { currentImageSrc: '', observer: null, swiperObserver: null, transitionBound: false, buttonTimer: null, // 初始化预览容器观察器与 swiper 切换监听 init() { this.setupImageContainerObserver(); this.setupSwiperListener(); }, // 监听预览容器出现;整个页面生命周期只建一个观察器 setupImageContainerObserver() { if (this.observer) return; const observerCallback = Utils.debounce((mutations) => { for (const mutation of mutations) { if (mutation.type === 'childList' || mutation.type === 'subtree') { if (document.querySelector('.imgViewDom')) { this.addOriginalImageButton(); break; } } } }, 300); this.observer = new MutationObserver(observerCallback); this.observer.observe(document.body, CONFIG.observerConfig); }, // swiper 的 transitionend 与 class 变化都收敛到同一个去重入口 setupSwiperListener() { if (this.transitionBound) return; this.transitionBound = true; // 监听swiper滑动事件 document.addEventListener('transitionend', (event) => { if (event.target.closest('.swiper-slide')) { this.addOriginalImageButton(); } }); // 使用MutationObserver监听active类变化 this.swiperObserver = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.attributeName === 'class' && mutation.target.classList.contains('swiper-slide') && mutation.target.classList.contains('swiper-slide-active')) { this.addOriginalImageButton(); } }); }); // 延迟设置swiper观察器 // 避免首屏时 swiper 尚未挂载 setTimeout(() => { document.querySelectorAll('.swiper-slide').forEach(slide => { this.swiperObserver.observe(slide, { attributes: true }); }); }, 1000); }, // 多条触发路径合并到一次延迟执行,避免同一时刻重复创建按钮 addOriginalImageButton() { if (this.buttonTimer) return; this.buttonTimer = setTimeout(() => { this.buttonTimer = null; this.insertOriginalImageButton(); }, 100); }, // 实际创建或更新按钮;同一张图片只保留一个按钮 insertOriginalImageButton() { const imgContainer = document.querySelector('.imgViewDom .swiper-slide-active img'); const toolbar = document.querySelector('.imgViewDom .img-preview-opt-box'); if (!imgContainer || !toolbar) return; const currentSrc = imgContainer.src; if (!currentSrc) return; // 如果按钮已存在且图片未变化,直接返回 const existingBtn = toolbar.querySelector('.original-image-btn'); if (existingBtn) { if (this.currentImageSrc === currentSrc) return; // 更新现有按钮 existingBtn.dataset.originalSrc = currentSrc; existingBtn.onclick = () => window.open(currentSrc, '_blank'); this.currentImageSrc = currentSrc; return; } // 创建新按钮 const button = document.createElement('button'); button.className = 'btn-img-preview fz-14 mx-8 original-image-btn'; button.dataset.originalSrc = currentSrc; button.title = '查看原图'; button.style.cssText = 'width:auto'; button.textContent = '查看原图'; button.onclick = (e) => { e.stopPropagation(); window.open(currentSrc, '_blank'); }; toolbar.appendChild(button); this.currentImageSrc = currentSrc; } }; // 广告处理模块 const AdProcessor = { pollStarted: false, init() { if (this.pollStarted) return; this.pollStarted = true; // 使用CSS已经隐藏了广告,这里处理额外逻辑 Utils.waitForElement('.toolbar-advert', () => { const closeBtn = document.querySelector('.toolbar-adver-btn'); if (closeBtn) { closeBtn.click(); } }); } }; // 代码块展开模块 const CodeExpandProcessor = { observer: null, init() { // 立即处理一次(首屏已有的代码块) this.clickExpandButtons(); if (this.observer) return; const debouncedClick = Utils.debounce(() => this.clickExpandButtons(), 200); this.observer = new MutationObserver(debouncedClick); this.observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] }); }, clickExpandButtons() { // 只处理仍处于「收起」状态的 pre const pres = document.querySelectorAll('pre.set-code-hide'); if (!pres.length) return; pres.forEach(pre => { // 已经点过就不再点,尊重用户的"收起代码块"操作 if (pre.dataset.autoExpanded) return; const btn = pre.querySelector('.hide-preCode-bt'); if (!btn) return; pre.dataset.autoExpanded = '1'; btn.click(); }); } }; // SPA 地址观察器只创建一次,避免每次 initScript 重跑时叠加监听 function setupUrlObserver() { if (urlObserver) return; // 监听URL变化(SPA页面) urlObserver = new MutationObserver(() => { const url = location.href; if (url === lastUrl) return; lastUrl = url; // 换页后允许各一次性轮询重新启动,然后重新初始化模块 LatexProcessor.iframePollStarted = false; CatalogProcessor.pollStarted = false; LinkRedirector.pollStarted = false; AdProcessor.pollStarted = false; // 重置初始化状态,重新初始化 initialized = false; setTimeout(initScript, 500); }); urlObserver.observe(document, { subtree: true, childList: true }); } // 主初始化函数 function initScript() { if (initialized) return; initialized = true; console.log('CSDN优化脚本初始化...'); // 初始化各模块 LatexProcessor.init(); LatexRawRevealer.init(); CatalogProcessor.init(); LinkRedirector.init(); ImageViewerEnhancer.init(); AdProcessor.init(); CodeExpandProcessor.init(); setupUrlObserver(); } // 页面加载完成后启动 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initScript); } else { initScript(); } // 确保脚本在AJAX加载的内容中也生效 $(document).on('DOMNodeInserted', Utils.debounce((e) => { if ($(e.target).hasClass('imgViewDom') || $(e.target).closest('.imgViewDom').length > 0) { ImageViewerEnhancer.addOriginalImageButton(); } }, 300)); })();