正文
增加 19 行删除 1685 行
12345678910111216 行未改动29303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744# 背景众所周知,洛谷分为国内站和国际站,而国内站只能查看自己的剪贴板和自己的文章,以及全站推荐的文章,而个人主页更是在最近的更新里改成了仅国际站可见。这时候我们便可以使用[洛谷保存站](https://www.luogu.me/),下文简称保存站。::::info[什么是洛谷保存站?]洛谷保存站是一个由 [Federico2903](https://www.luogu.com.cn/user/381949) 运营的第三方网站,可以实现保存洛谷的剪贴板、用户主页、文章等,并且不会因地区限制而访问失败。::::之前也有过检测到无法访问就跳转到保存站的脚本,但是无一例外都必须要去访问保存站才能查看,而保存站终究还是第三方网站,界面和洛谷大相径庭,在查找资料时需要多次跳转,容易打断思路,而且也无法快速跳转到洛谷相关页面。于是DeepSeek(和我)花了一下午的时间制作了这个脚本,能够通过 [保存站 API](https://api.luogu.me) ([文档](https://luogu-saver-next.apifox.cn/)) 获取用户、文章、剪贴板信息,嵌入到洛谷当中。# 功能- 非自己、管理员的主页从保存站获取个人简介并追加卡片。16 行未改动# 原理## 个人简介通过 API 获取个人简介 Markdown 渲染后的 HTML ,然后追加一个卡片,将获取到的 HTML 嵌入。## 剪贴板访问一篇无法访问的剪贴板时,会提示安全访问中心,是否要跳转到 www.luogu.com/xxx ,检测到这个页面后,脚本会在页面上覆盖一个全屏 iframe 访问模版剪贴板,之所以用 iframe 是为了尽可能实现原生体验,实现 1:1 还原洛谷界面,并且能够实现地址栏不动,然后通过动态检测替换掉模版内容,并创建一个更新按钮。## 专栏大部分原理同剪贴板,但是需要做的事更多了,因为右侧的目录并不会自动生成,所以脚本会先遍历文章,然后在右侧创建目录,但是会从模版的目录里提取出相关 CSS 然后使用。并且还会将操作栏的点赞、收藏、不推荐修改为不可点击,并替换文本为保存站的点赞数。然后通过洛谷官方 API 获得评论信息并追加。# 使用受限于原理限制,需要手动创建一个可以正常访问的剪贴板和文章,剪贴板没有特殊要求,但文章需要有三级标题,比如```markdown# 1## 2### 3```然后在专栏中发一个评论,并确保点赞数和收藏数为0(可以设置为私有)。然后在浏览器中安装 [Tampermonkey](https://www.tampermonkey.net) 。然后点击Tampermonkey扩展图标,在弹出的菜单中点击“添加新脚本”,在编辑页面中删掉原来的内容,将以下内容粘贴进去,然后按下 Ctrl+S 或者 Command+S (macOS) 保存,刷新原有页面即可生效。部分浏览器需要在插件设置里给 Tampermonkey 开启“允许用户脚本”权限。::::info[脚本]```javascript// ==UserScript==// @name LGSinLG// @namespace https://www.luogu.com.cn/user/1816684// @version 1.0.18// @description 洛谷国内站:用户主页添加个人介绍卡片;陌生剪切板/文章通过 iframe + API 替换内容,支持 CP OAuth 自动登录和工作流更新;修复多实例刷新问题;替换文章分类、点赞收藏数(纯数字)并禁止交互;支持多操作栏;动态替换右侧目录(保留原生样式);修复加载卡死和跨域自动刷新;iframe 内非锚点链接在顶层跳转;修复 heading-anchor 锚点(已移除);安全页超时放弃接管,不再刷新;修改页面标题格式;头像链接放行保留抽屉菜单;修复时间显示为本地时间;使用全局事件委托彻底解决编辑按钮跳转;主页更新按钮宽度自适应;恢复点赞收藏数及禁用交互功能;检测自己主页不再追加个人介绍卡片;修复浏览器返回后页面不更新的问题;修复 getLoginUid 选择器以适配新版导航栏;修复未保存文章/剪切板时页面卡死在加载中,增加“保存”按钮,修复后退与重试;修复图片宽度溢出问题;注入 Shiki 代码块专用样式,完美显示代码高亮、行号,不影响侧边栏及其他区域;添加 md-block 折叠展开(按钮位于标题最右侧);代码块复制按钮;修复 md-block 标题图标与文字重叠;移除评论区删除功能;去除保存站HTML中的文章内部锚点;修复文章时间误替换评论区时间;移除 Uptime-Kuma 伪装;新增评论区接管(复用模板结构,游标分页,暂不显示认证徽章,修复时间戳解析);修复加载更多按钮样式;等待评论区懒加载完成后再接管// @author https://www.luogu.com.cn/user/1816684// @match *://*.luogu.com.cn/*// @match *://*.luogu.me/*// @grant GM_xmlhttpRequest// @grant GM_setValue// @grant GM_getValue// ==/UserScript==(function() {'use strict';console.log('[LGSinLG] 脚本启动,版本 1.0.18', new Date().toISOString());window.addEventListener('unhandledrejection', function(event) {console.error('[LGSinLG] 未捕获的 Promise 拒绝:', event.reason);console.error('[LGSinLG] 当前 URL:', location.href);if (event.reason && event.reason.stack) {console.error('[LGSinLG] 堆栈:', event.reason.stack);}});if (window.self !== window.top) return;if (window.__LGSinLG_script_running) return;window.__LGSinLG_script_running = true;const USER_CONFIG = {templatePasteId: 'o1lvqcmv',templateArticleId: 'omfzy7i3',colorMap: {'Green': '#52c41a','Blue': '#3498db','Red': '#e74c3c','Orange': '#f39c12','Purple': '#9b59b6','Gray': '#95a5a6','Cheater': '#e74c3c',},categoryMap: {1: '个人纪录',2: '题解',3: '科技·工程',4: '算法·理论',5: '生活·游记',6: '学习·文化课',7: '休闲·娱乐',8: '闲话'}};// Shiki 代码块专用样式const SHIKI_CSS = `.shiki, .shiki span {color: var(--shiki-light, #24292e);}.shiki {background-color: var(--shiki-light-bg, #f6f8fa);}@media (prefers-color-scheme: dark) {.shiki, .shiki span {color: var(--shiki-dark, #c9d1d9);}.shiki {background-color: var(--shiki-dark-bg, #0d1117);}}pre.shiki {padding: 16px;border-radius: 8px;border: 1px solid #d0d7de;background-color: #f6f8fa !important;overflow-x: auto;font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace;font-size: 13px;line-height: 1.5;tab-size: 4;margin: 1em 0;}@media (prefers-color-scheme: dark) {pre.shiki {background-color: #0d1117 !important;border-color: #30363d;}}.shiki {counter-reset: line;}.shiki .line::before {counter-increment: line;content: counter(line);display: inline-block;width: 2em;margin-right: 1em;text-align: right;color: #8c959f;user-select: none;}@media (prefers-color-scheme: dark) {.shiki .line::before {color: #484f58;}}.code-line.highlight {background: rgba(255, 229, 100, 0.25);}.md-block.info,.md-block.warning,.md-block.success,.md-block.error {border: 0 solid rgba(228, 228, 228, 0);border-left-width: 6px;padding: 10px;margin: 12px 0;}.md-block.info { border-left-color: #7da7ff; }.md-block.warning { border-left-color: #ffb454; }.md-block.success { border-left-color: #4dd27a; }.md-block.error { border-left-color: #ff5757; }.md-block > .md-block-title {font-weight: 700;display: flex;justify-content: space-between;align-items: center;color: inherit;margin-bottom: 4px;position: relative;padding-left: 1.8em;}.md-block.info > .md-block-title { color: #7da7ff; }.md-block.warning > .md-block-title { color: #ffb454; }.md-block.success > .md-block-title { color: #4dd27a; }.md-block.error > .md-block-title { color: #ff5757; }.md-block > .md-block-body { margin-top: 4px; }.md-block > .md-block-body > p:last-child { margin-bottom: 0; }.md-block > .md-block-title::before {content: '';display: inline-block;width: 1em;height: 1em;background-color: currentColor;-webkit-mask-repeat: no-repeat;mask-repeat: no-repeat;-webkit-mask-size: contain;mask-size: contain;position: absolute;left: 0.2em;top: 50%;transform: translateY(-50%);}.md-block.success > .md-block-title::before {-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM369 209L241 337c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L335 175c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/></svg>');mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM369 209L241 337c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L335 175c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/></svg>');}.md-block.warning > .md-block-title::before {-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zm0-384c13.3 0 24 10.7 24 24V264c0 13.3-10.7 24-24 24s-24-10.7-24-24V152c0-13.3 10.7-24 24-24zM224 352a32 32 0 1 1 64 0 32 32 0 1 1 -64 0z"/></svg>');mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zm0-384c13.3 0 24 10.7 24 24V264c0 13.3-10.7 24-24 24s-24-10.7-24-24V152c0-13.3 10.7-24 24-24zM224 352a32 32 0 1 1 64 0 32 32 0 1 1 -64 0z"/></svg>');}.md-block.info > .md-block-title::before {-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"/></svg>');mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"/></svg>');}.md-block.error > .md-block-title::before {-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM175 175c9.4-9.4 24.6-9.4 33.9 0l47 47 47-47c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-47 47 47 47c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0l-47-47-47 47c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l47-47-47-47c-9.4-9.4-9.4-24.6 0-33.9z"/></svg>');mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM175 175c9.4-9.4 24.6-9.4 33.9 0l47 47 47-47c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-47 47 47 47c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0l-47-47-47 47c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l47-47-47-47c-9.4-9.4-9.4-24.6 0-33.9z"/></svg>');}.heading-pin-icon {width: 18px;height: 18px;stroke-width: 2;}.md-block-title {cursor: pointer;user-select: none;}.toggle-icon {display: inline-block;transition: transform 0.25s;margin-left: 0.5em;font-size: 0.9em;line-height: 1;flex-shrink: 0;}.toggle-icon.collapsed {transform: rotate(-90deg);}.shiki-wrapper {position: relative;}.shiki-copy-btn {position: absolute;top: 8px;right: 8px;background: rgba(0,0,0,0.05);border: 1px solid #d0d7de;border-radius: 4px;padding: 2px 8px;font-size: 12px;cursor: pointer;opacity: 0;transition: opacity 0.2s;z-index: 5;}.shiki-wrapper:hover .shiki-copy-btn {opacity: 1;}@media (prefers-color-scheme: dark) {.shiki-copy-btn {background: rgba(255,255,255,0.05);border-color: #30363d;}}/* 行号边距微调 */.shiki .line {display: block;padding-left: 3.5em; /* 为行号留出固定空间,原来的 ::before 用了 2em + margin-right 1em,这里再加一点内边距 */text-indent: -3.5em; /* 让行号向左突出,保持代码对齐 */}/* 深色模式下普通 pre 的补充 */pre:not(.shiki) {background-color: #f6f8fa !important;border-color: #d0d7de;}@media (prefers-color-scheme: dark) {pre:not(.shiki) {background-color: #0d1117 !important;border-color: #30363d;}}`;// ---------- 工具函数 ----------function getUserIdFromUrl() {const m = location.pathname.match(/^\/user\/(\d+)\/?$/);return m ? m[1] : null;}function getPasteIdFromUrl() {const m = location.pathname.match(/\/paste\/([a-zA-Z0-9]+)/);return m ? m[1] : null;}function getArticleIdFromUrl() {const m = location.pathname.match(/\/article\/([a-zA-Z0-9]+)/);return m ? m[1] : null;}function parseApiTime(rawTime) {if (!rawTime) return null;if (typeof rawTime === 'number') {return new Date(rawTime * 1000).toISOString();}if (typeof rawTime === 'string') {const d = new Date(rawTime);if (!isNaN(d.getTime())) return d.toISOString();}return null;}function formatTime(isoStr) {if (!isoStr) return '未知';const d = new Date(isoStr);if (isNaN(d.getTime())) return '未知';const pad = n => String(n).padStart(2, '0');return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;}function getRelativeTime(isoStr) {if (!isoStr) return '';const now = new Date();const d = new Date(isoStr);const diff = now - d;const seconds = Math.floor(diff / 1000);if (seconds < 60) return '刚刚';const minutes = Math.floor(seconds / 60);if (minutes < 60) return `${minutes} 分钟前`;const hours = Math.floor(minutes / 60);if (hours < 24) return `${hours} 小时前`;const days = Math.floor(hours / 24);if (days < 30) return `${days} 天前`;const months = Math.floor(days / 30);if (months < 12) return `${months} 个月前`;const years = Math.floor(months / 12);return `${years} 年前`;}function constrainImages(container) {if (!container) return;const imgs = container.querySelectorAll('img');imgs.forEach(img => {img.style.maxWidth = '100%';img.style.height = 'auto';});}function forceExternalLinks(container) {if (!container) return;const links = container.querySelectorAll('a');links.forEach(a => {let href = a.getAttribute('href');if (!href) return;if (href.startsWith('#')) return;if (href.startsWith('/')) {href = `https://www.luogu.com.cn${href}`;a.setAttribute('href', href);}a.setAttribute('rel', 'noopener noreferrer');});}function createClickableUsername(name, color, userId) {const span = document.createElement('span');span.style.cssText = `font-weight: bold; color: ${color}; cursor: pointer;`;span.textContent = name;span.addEventListener('click', function(e) {e.preventDefault();window.top.location.href = `/user/${userId}`;});return span;}function injectShikiCSS(doc) {if (!doc || !doc.head) return;const style = doc.createElement('style');style.textContent = SHIKI_CSS;doc.head.appendChild(style);console.log('[LGSinLG] Shiki 代码块样式已注入');}function addMdBlockToggle(doc) {if (!doc || !doc.body) return;const blocks = doc.querySelectorAll('.md-block');blocks.forEach(block => {const title = block.querySelector('.md-block-title');if (!title || title.dataset.toggleBound) return;const body = block.querySelector('.md-block-body');if (!body) return;const icon = doc.createElement('span');icon.className = 'toggle-icon';icon.textContent = '▸';title.appendChild(icon);title.addEventListener('click', () => {const collapsed = icon.classList.toggle('collapsed');body.style.display = collapsed ? 'none' : '';});title.style.cursor = 'pointer';title.dataset.toggleBound = 'true';});console.log('[LGSinLG] md-block 折叠功能已激活');}function addShikiCopyButtons(doc) {if (!doc || !doc.body) return;const allPres = doc.querySelectorAll('pre');allPres.forEach(pre => {// 已处理过则跳过if (pre.dataset.lgsCopyProcessed) return;pre.dataset.lgsCopyProcessed = 'true';// 如果 pre 中还没有 .line 结构(即非 Shiki 渲染),则为其生成行号结构if (!pre.querySelector('.line') && !pre.classList.contains('shiki')) {// 获取纯文本(保留换行)const text = pre.textContent || '';const lines = text.split('\n');// 清空 pre 内容pre.innerHTML = '';lines.forEach((line, i) => {const span = doc.createElement('span');span.className = 'line';span.textContent = line;pre.appendChild(span);// 除了最后一行,插入换行节点,模拟原始换行if (i < lines.length - 1) {pre.appendChild(doc.createTextNode('\n'));}});// 添加 .shiki 类,复用已写好的行号 CSS(.shiki .line::before)pre.classList.add('shiki');}// 避免重复包裹if (pre.parentElement && pre.parentElement.classList.contains('shiki-wrapper')) return;// 包裹 wrapper 并添加按钮const wrapper = doc.createElement('div');wrapper.className = 'shiki-wrapper';pre.parentNode.insertBefore(wrapper, pre);wrapper.appendChild(pre);// 如果 pre 没有 .shiki 类(极少情况),补充基础样式if (!pre.classList.contains('shiki')) {pre.style.padding = '16px';pre.style.borderRadius = '8px';pre.style.border = '1px solid #d0d7de';pre.style.backgroundColor = '#f6f8fa';pre.style.overflowX = 'auto';pre.style.fontFamily = '"SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace';pre.style.fontSize = '13px';pre.style.lineHeight = '1.5';pre.style.margin = '1em 0';}const btn = doc.createElement('button');btn.className = 'shiki-copy-btn';btn.textContent = '复制';btn.addEventListener('click', () => {// 复制时只取纯文本,自动忽略行号(伪元素)const code = pre.textContent || '';navigator.clipboard.writeText(code).then(() => {btn.textContent = '已复制';setTimeout(() => { btn.textContent = '复制'; }, 2000);}).catch(() => {const ta = doc.createElement('textarea');ta.value = code;ta.style.position = 'fixed';ta.style.opacity = '0';doc.body.appendChild(ta);ta.select();doc.execCommand('copy');doc.body.removeChild(ta);btn.textContent = '已复制';setTimeout(() => { btn.textContent = '复制'; }, 2000);});});wrapper.appendChild(btn);});console.log('[LGSinLG] 代码块复制按钮已添加(含行号适配)');}// ---------- 个人介绍卡片 ----------const CARD_ID = 'lgsinlg-intro-card';function isAdminUser() {const rows = document.querySelectorAll('.l-flex-info-row');for (const row of rows) {const span = row.querySelector('span');if (span && span.textContent.trim() === '用户类型') {const right = row.querySelector('.right');if (right && right.textContent.trim() === '管理员') return true;}}return false;}function removeUserCardIfExists() {const card = document.getElementById(CARD_ID);if (card) card.remove();}function getLoginUid() {const selectors = ['.lfe-header a[href^="/user/"]','.header a[href^="/user/"]','a[href^="/user/"].avatar-link','a[href^="/user/"].user-link','.user-menu a[href^="/user/"]','.avatar a[href^="/user/"]','nav a[href^="/user/"]','.navbar a[href^="/user/"]','.app-header a[href^="/user/"]'];for (const sel of selectors) {const el = document.querySelector(sel);if (el) {const match = el.getAttribute('href').match(/\/user\/(\d+)/);if (match) {console.log('[LGSinLG] getLoginUid 匹配到:', sel, 'ID:', match[1]);return match[1];}}}console.warn('[LGSinLG] getLoginUid 未找到登录用户ID');return null;}function getOrCreateCard(uid) {if (isAdminUser()) return null;let card = document.getElementById(CARD_ID);if (card && card.dataset.uid === uid) {return { card, contentDiv: card.querySelector('.lfe-marked-wrap.introduction'), refreshBtn: card.querySelector('button') };}if (card) card.remove();const container = document.querySelector('.sidebar-container > .main');if (!container) return null;const templateCard = container.querySelector('.l-card');if (!templateCard) return null;card = document.createElement('div');card.id = CARD_ID;card.dataset.uid = uid;card.className = templateCard.className;for (const attr of templateCard.attributes) {if (attr.name.startsWith('data-v-')) card.setAttribute(attr.name, attr.value);}const header = document.createElement('div');header.className = 'header';header.style.cssText = 'display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;';const h3 = document.createElement('h3');h3.style.margin = '0'; h3.textContent = '个人介绍';const editSpan = document.createElement('span');editSpan.className = 'edit-button';const refreshBtn = document.createElement('button');refreshBtn.className = 'lform-size-small';refreshBtn.type = 'button';refreshBtn.textContent = '更新';const style = refreshBtn.style;style.appearance = 'button';style.backgroundColor = 'rgba(52,152,219,0)';style.backgroundImage = 'none';style.borderColor = 'rgb(52,152,219)';style.borderRadius = '3px';style.borderStyle = 'solid';style.borderWidth = '1px';style.boxSizing = 'border-box';style.color = 'rgb(52,152,219)';style.cursor = 'pointer';style.display = 'block';style.fontFamily = '-apple-system, "system-ui", "Helvetica Neue", "PingFang SC", "Noto Sans", "Noto Sans SC", "Source Sans Pro", "Source Han Sans", "Segoe UI", Arial, "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif';style.fontSize = '14px';style.fontWeight = '400';style.lineHeight = '21px';style.margin = '0';style.minWidth = '44px';style.outline = 'none';style.overflow = 'visible';style.padding = '2px 12px';style.textAlign = 'center';style.textIndent = '0';style.textShadow = 'none';style.textTransform = 'none';style.verticalAlign = 'middle';style.wordSpacing = '0';editSpan.appendChild(refreshBtn);header.appendChild(h3);header.appendChild(editSpan);card.appendChild(header);const contentDiv = document.createElement('div');contentDiv.className = 'lfe-marked-wrap introduction';contentDiv.style.cssText = 'overflow-wrap: break-word; word-break: break-all;';card.appendChild(contentDiv);container.appendChild(card);refreshBtn.addEventListener('click', () => handleRefresh(uid, refreshBtn, contentDiv));return { card, contentDiv, refreshBtn };}function fetchAndUpdateCard(uid) {if (isAdminUser()) { removeUserCardIfExists(); return; }const elements = getOrCreateCard(uid);if (!elements) {if (!fetchAndUpdateCard._retryCount) fetchAndUpdateCard._retryCount = 0;if (fetchAndUpdateCard._retryCount < 10) {fetchAndUpdateCard._retryCount++;setTimeout(() => fetchAndUpdateCard(uid), 300);} else {console.warn('[LGSinLG] 卡片容器多次重试仍未出现,放弃');fetchAndUpdateCard._retryCount = 0;}return;}fetchAndUpdateCard._retryCount = 0;elements.contentDiv.innerHTML = '加载中...';GM_xmlhttpRequest({method: 'GET',url: `https://api.luogu.me/user/query/${uid}`,onload: function(res) {try {const data = JSON.parse(res.responseText);if (data.code === 200 && data.data) {const intro = data.data.renderedIntroduction || '<p>暂无个人介绍</p>';elements.contentDiv.innerHTML = intro;constrainImages(elements.contentDiv);// 移除 heading-anchor 锚点const headingAnchors = elements.contentDiv.querySelectorAll('a.heading-anchor');headingAnchors.forEach(a => a.remove());} else {elements.contentDiv.innerHTML = '<p>获取简介失败</p>';}} catch (e) {elements.contentDiv.innerHTML = '<p>数据解析错误</p>';}},onerror: function() {elements.contentDiv.innerHTML = '<p>网络请求失败</p>';}});}function handleRefresh(uid, btn, contentDiv) {if (btn.disabled) return;btn.textContent = '已发送';btn.disabled = true;GM_xmlhttpRequest({method: 'POST',url: `https://api.luogu.me/user/${uid}/refresh`,onload: function(res) {try {const data = JSON.parse(res.responseText);if (data.code === 200) {GM_xmlhttpRequest({method: 'GET',url: `https://api.luogu.me/user/query/${uid}`,onload: function(resp) {try {const p = JSON.parse(resp.responseText);if (p.code === 200 && p.data) {contentDiv.innerHTML = p.data.renderedIntroduction || '<p>暂无个人介绍</p>';constrainImages(contentDiv);// 刷新后同样移除 heading-anchorconst headingAnchors = contentDiv.querySelectorAll('a.heading-anchor');headingAnchors.forEach(a => a.remove());} else {contentDiv.innerHTML = '<p>获取简介失败</p>';}} catch (e) {contentDiv.innerHTML = '<p>数据解析错误</p>';}btn.textContent = '更新'; btn.disabled = false;},onerror: function() {contentDiv.innerHTML = '<p>网络请求失败</p>';btn.textContent = '更新'; btn.disabled = false;}});} else {btn.textContent = '更新'; btn.disabled = false;}} catch (e) {btn.textContent = '更新'; btn.disabled = false;}},onerror: function() {btn.textContent = '更新'; btn.disabled = false;}});}// ---------- 接管流程公共部分 ----------function waitForIframeLoad(iframe, timeoutMs = 20000) {return new Promise((resolve, reject) => {const timer = setTimeout(() => {console.warn('[LGSinLG] iframe 加载超时');reject(new Error('iframe 加载超时'));}, timeoutMs);const onLoad = () => { clearTimeout(timer); resolve(); };const onError = () => {console.warn('[LGSinLG] iframe 加载失败');clearTimeout(timer);reject(new Error('iframe 加载失败'));};iframe.addEventListener('load', onLoad, { once: true });iframe.addEventListener('error', onError, { once: true });try {const doc = iframe.contentDocument || iframe.contentWindow.document;if (doc && doc.readyState === 'complete') {clearTimeout(timer);resolve();}} catch (e) {}});}function setupLinkInterceptor(doc) {if (!doc || !doc.body) return;const handler = (e) => {const target = e.target.closest('a');if (!target) return;const href = target.getAttribute('href');if (!href || href.startsWith('#') || href.startsWith('javascript:')) return;if (target.closest('.avatar')) {console.log('[LGSinLG] 头像链接放行,不拦截');return;}e.preventDefault();e.stopPropagation();console.log('[LGSinLG] 顶层跳转:', href);window.top.location.href = href;};doc.body.removeEventListener('click', handler, true);doc.body.addEventListener('click', handler, true);}function handlePastePage(pasteId) {console.log('[LGSinLG] 进入剪切板接管,pasteId:', pasteId);if (pasteId === USER_CONFIG.templatePasteId) return;if (window.__LGSinLG_paste_handled) return;window.__LGSinLG_paste_handled = true;const oldIframe = document.getElementById('lgsinlg-paste-iframe');if (oldIframe) oldIframe.remove();document.body.innerHTML = `<div id="lgsinlg-loading" style="text-align:center; padding:50px;">加载中…</div><div id="lgsinlg-error" style="display:none; text-align:center; padding:50px;"><p id="lgsinlg-error-msg"></p><button id="lgsinlg-retry-btn" style="margin-top:20px; padding:8px 20px; background:#3498db; color:#fff; border:none; border-radius:4px; cursor:pointer;">重试</button></div>`;document.getElementById('lgsinlg-retry-btn').addEventListener('click', () => location.reload());const iframe = document.createElement('iframe');iframe.id = 'lgsinlg-paste-iframe';iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox allow-forms');iframe.style.cssText = 'position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; border: none; z-index: 9999; display: none;';document.body.appendChild(iframe);const iframeLoad = waitForIframeLoad(iframe, 20000);iframe.src = `https://www.luogu.com.cn/paste/${USER_CONFIG.templatePasteId}`;document.title = '云剪贴板 - 洛谷|计算机教育新生态';const apiPromise = new Promise((resolve, reject) => {GM_xmlhttpRequest({method: 'GET',url: `https://api.luogu.me/paste/query/${pasteId}`,onload(res) {try {const data = JSON.parse(res.responseText);if (data.code === 200 && data.data) resolve(data.data);else reject(new Error(data.message || '接口返回错误'));} catch (e) { reject(new Error('数据解析失败')); }},onerror() { reject(new Error('网络请求失败')); }});});function showError(msg, id, type) {document.getElementById('lgsinlg-loading').style.display = 'none';document.getElementById('lgsinlg-error').style.display = 'block';document.getElementById('lgsinlg-error-msg').textContent = msg;const oldSaveBtn = document.getElementById('lgsinlg-save-btn');if (oldSaveBtn) oldSaveBtn.remove();const saveBtn = document.createElement('button');saveBtn.id = 'lgsinlg-save-btn';saveBtn.style.cssText = 'margin-left: 10px; padding: 8px 20px; background: #52c41a; color: #fff; border: none; border-radius: 4px; cursor: pointer;';saveBtn.textContent = '保存';saveBtn.addEventListener('click', () => {triggerWorkflowWithLogin(saveBtn, id, type, () => location.reload());});document.getElementById('lgsinlg-error').appendChild(saveBtn);const ifr = document.getElementById('lgsinlg-paste-iframe');if (ifr) ifr.remove();window.__LGSinLG_paste_handled = false;window.__LGSinLG_active = false;}Promise.all([iframeLoad, apiPromise]).then(([_, pasteData]) => {console.log('[LGSinLG] 剪切板 iframe 和 API 加载完成');const performCoreReplace = () => {let doc;try {doc = iframe.contentDocument || iframe.contentWindow.document;} catch (e) {handleAutoRefresh(e);return false;}if (!doc) return false;const markedDiv = doc.querySelector('.marked');const timeCaption = doc.querySelector('.content-card-top .author .lfe-caption:not(.author-margin)');const actionsDiv = doc.querySelector('.actions');if (!markedDiv || !timeCaption || !actionsDiv) return false;markedDiv.innerHTML = pasteData.renderedContent || '<p>暂无内容</p>';constrainImages(markedDiv);forceExternalLinks(markedDiv);// 移除 heading-anchor 锚点const headingAnchors = markedDiv.querySelectorAll('a.heading-anchor');headingAnchors.forEach(a => a.remove());injectShikiCSS(doc);const authorCaption = doc.querySelector('.author .lfe-caption.author-margin');if (authorCaption) {const color = USER_CONFIG.colorMap[pasteData.author.color] || '#000';authorCaption.innerHTML = '作者: ';authorCaption.appendChild(createClickableUsername(pasteData.author.name, color, pasteData.author.id));}const createdTime = formatTime(pasteData.createdAt);const updatedTime = formatTime(pasteData.updatedAt);timeCaption.innerHTML = `发表时间: <time>${createdTime}</time> | 更新: <time>${updatedTime}</time>`;const buttons = actionsDiv.querySelectorAll('button');buttons.forEach(btn => { btn.style.display = 'none'; });const updateBtn = document.createElement('button');updateBtn.type = 'button'; updateBtn.textContent = '更新';updateBtn.style.cssText = 'background: rgb(52, 152, 219); border: 1px solid rgb(52, 152, 219); border-radius: 3px; color: #fff; cursor: pointer; font-size: 14px; padding: 4px 12px;';updateBtn.addEventListener('click', () => triggerWorkflowWithLogin(updateBtn, pasteId, 'paste'));actionsDiv.appendChild(updateBtn);return true;};let attempts = 0;const interval = setInterval(() => {try {if (performCoreReplace() || ++attempts >= 50) {clearInterval(interval);if (!performCoreReplace()) {showError('页面结构加载超时', pasteId, 'paste');return;}const doc = iframe.contentDocument || iframe.contentWindow.document;setupLinkInterceptor(doc);setupSourceObserver(doc, pasteData.content);addMdBlockToggle(doc);addShikiCopyButtons(doc);document.getElementById('lgsinlg-loading').style.display = 'none';iframe.style.display = '';window.__LGSinLG_active = true;console.log('[LGSinLG] 剪切板接管完成');}} catch (e) {clearInterval(interval);console.error('[LGSinLG] 剪切板轮询异常', e);handleAutoRefresh(e);}}, 200);function setupSourceObserver(doc, rawContent) {const TARGET_SELECTOR = '.card.padding-default .code-card-top pre';const PROCESSED_ATTR = 'data-lgs-processed';const initialPre = doc.querySelector(TARGET_SELECTOR);if (initialPre && !initialPre.hasAttribute(PROCESSED_ATTR)) {initialPre.textContent = rawContent;initialPre.setAttribute(PROCESSED_ATTR, 'true');}const observer = new MutationObserver(() => {const pre = doc.querySelector(TARGET_SELECTOR);if (pre && !pre.hasAttribute(PROCESSED_ATTR)) {pre.textContent = rawContent;pre.setAttribute(PROCESSED_ATTR, 'true');}});observer.observe(doc.body, { childList: true, subtree: true });}}).catch(err => {console.error('[LGSinLG] 剪切板 Promise 异常', err);showError('该剪切板尚未被保存站收录', pasteId, 'paste');});}function handleArticlePage(articleId) {console.log('[LGSinLG] 进入文章接管,articleId:', articleId);if (articleId === USER_CONFIG.templateArticleId) return;if (window.__LGSinLG_article_handled) return;window.__LGSinLG_article_handled = true;document.body.innerHTML = `<div id="lgsinlg-loading" style="text-align:center; padding:50px;">加载中…</div><div id="lgsinlg-error" style="display:none; text-align:center; padding:50px;"><p id="lgsinlg-error-msg"></p><button id="lgsinlg-retry-btn" style="margin-top:20px; padding:8px 20px; background:#3498db; color:#fff; border:none; border-radius:4px; cursor:pointer;">重试</button></div>`;document.getElementById('lgsinlg-retry-btn').addEventListener('click', () => location.reload());const iframe = document.createElement('iframe');iframe.id = 'lgsinlg-article-iframe';iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox allow-forms');iframe.style.cssText = 'position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; border: none; z-index: 9999; display: none;';document.body.appendChild(iframe);const iframeLoad = waitForIframeLoad(iframe, 20000);iframe.src = `https://www.luogu.com.cn/article/${USER_CONFIG.templateArticleId}`;const apiPromise = new Promise((resolve, reject) => {GM_xmlhttpRequest({method: 'GET',url: `https://api.luogu.me/article/query/${articleId}`,onload(res) {try {const data = JSON.parse(res.responseText);if (data.code === 200 && data.data) resolve(data.data);else reject(new Error(data.message || '接口返回错误'));} catch (e) { reject(new Error('数据解析失败')); }},onerror() { reject(new Error('网络请求失败')); }});});function showError(msg, id, type) {document.getElementById('lgsinlg-loading').style.display = 'none';document.getElementById('lgsinlg-error').style.display = 'block';document.getElementById('lgsinlg-error-msg').textContent = msg;const oldSaveBtn = document.getElementById('lgsinlg-save-btn');if (oldSaveBtn) oldSaveBtn.remove();const saveBtn = document.createElement('button');saveBtn.id = 'lgsinlg-save-btn';saveBtn.style.cssText = 'margin-left: 10px; padding: 8px 20px; background: #52c41a; color: #fff; border: none; border-radius: 4px; cursor: pointer;';saveBtn.textContent = '保存';saveBtn.addEventListener('click', () => {triggerWorkflowWithLogin(saveBtn, id, type, () => location.reload());});document.getElementById('lgsinlg-error').appendChild(saveBtn);const ifr = document.getElementById('lgsinlg-article-iframe');if (ifr) ifr.remove();window.__LGSinLG_article_handled = false;window.__LGSinLG_active = false;}Promise.all([iframeLoad, apiPromise]).then(([_, articleData]) => {console.log('[LGSinLG] 文章 iframe 和 API 加载完成,开始替换');document.title = (articleData.title || '文章') + ' - 洛谷专栏';const performCoreReplace = () => {let doc;try {doc = iframe.contentDocument || iframe.contentWindow.document;} catch (e) {handleAutoRefresh(e);return false;}if (!doc) return false;const titleEl = doc.querySelector('h1') || doc.querySelector('.article-title') || doc.querySelector('[data-role="title"]');const contentSelectors = ['.marked', 'article .content', '#article-content', '.article-body', '.post-content', '.entry-content', '[data-role="content"]', '.lfe-marked-wrap'];let contentDiv = null;for (const sel of contentSelectors) { contentDiv = doc.querySelector(sel); if (contentDiv) break; }const authorContainer = doc.querySelector('.author') || doc.querySelector('[data-role="author"]');let timeCaption = doc.querySelector('.article-banner .meta time[datetime]') || doc.querySelector('.article-banner time[datetime]');const updateInfo = doc.querySelector('.update-info');if (!contentDiv) return false;if (titleEl) { titleEl.textContent = articleData.title; if (doc.title) doc.title = articleData.title; }contentDiv.innerHTML = articleData.renderedContent || '<p>暂无内容</p>';constrainImages(contentDiv);forceExternalLinks(contentDiv);// 移除 heading-anchor 锚点(文章接管中保留原有处理)const headingAnchors = contentDiv.querySelectorAll('a.heading-anchor');headingAnchors.forEach(a => a.remove());injectShikiCSS(doc);const headings = contentDiv.querySelectorAll('h1, h2, h3, h4, h5, h6');headings.forEach((heading, index) => {heading.id = `lgs-toc-${index}`;});const tocContainer = doc.querySelector('.toc');if (tocContainer) {const tocUl = tocContainer.querySelector('ul');if (tocUl) {const templateLi = tocUl.querySelector('li');const templateSpan = templateLi ? templateLi.querySelector('span') : null;tocUl.innerHTML = '';if (headings.length > 0 && templateLi) {headings.forEach((heading, index) => {const li = templateLi.cloneNode(false);li.className = `title-${parseInt(heading.tagName.charAt(1)) - 1}`;li.title = heading.textContent.trim();let span;if (templateSpan) {span = templateSpan.cloneNode(false);} else {span = document.createElement('span');for (const attr of li.attributes) {if (attr.name.startsWith('data-v-')) span.setAttribute(attr.name, attr.value);}}span.textContent = heading.textContent.trim();li.appendChild(span);li.addEventListener('click', (e) => {e.preventDefault();heading.scrollIntoView({ behavior: 'smooth', block: 'start' });});tocUl.appendChild(li);});tocContainer.style.display = '';} else {tocContainer.style.display = 'none';}}}if (authorContainer) {const avatarImg = authorContainer.querySelector('.avatar');if (avatarImg) avatarImg.src = `https://cdn.luogu.com.cn/upload/usericon/${articleData.author.id}.png`;const userNameDiv = authorContainer.querySelector('.user-name');if (userNameDiv) {const color = USER_CONFIG.colorMap[articleData.author.color] || '#000';userNameDiv.innerHTML = '';userNameDiv.appendChild(createClickableUsername(articleData.author.name, color, articleData.author.id));}const badges = authorContainer.querySelectorAll('a[target="_blank"], .fa-badge-check');badges.forEach(b => b.remove());}if (timeCaption) {timeCaption.innerHTML = `发布于 ${formatTime(articleData.createdAt)} | 更新于 ${formatTime(articleData.updatedAt)}`;}if (updateInfo) {updateInfo.innerHTML = '';const authorSpan = document.createElement('span');authorSpan.textContent = '作者:';const color = USER_CONFIG.colorMap[articleData.author.color] || '#000';authorSpan.appendChild(createClickableUsername(articleData.author.name, color, articleData.author.id));updateInfo.appendChild(authorSpan);const sep = document.createTextNode(' \u00a0\u00a0 ');updateInfo.appendChild(sep);const timeSpan = document.createElement('span');timeSpan.textContent = '创建时间:';const timeTag = document.createElement('time');timeTag.setAttribute('datetime', articleData.createdAt);timeTag.textContent = formatTime(articleData.createdAt);timeSpan.appendChild(timeTag);updateInfo.appendChild(timeSpan);}hijackActionButtons(doc, articleData, articleId);function replaceCategory(doc, categoryId) {const categoryName = USER_CONFIG.categoryMap[categoryId] || `分类${categoryId}`;const labelDivs = doc.querySelectorAll('.label');labelDivs.forEach(label => {if (label.textContent.trim() === '分类') {const parent = label.parentElement;if (!parent) return;const nextDiv = parent.querySelector(':scope > div:not(.label)');if (nextDiv) {const span = nextDiv.querySelector('span');if (span) span.textContent = categoryName;else nextDiv.textContent = categoryName;}}});const categoryLinks = doc.querySelectorAll('a[href^="/article?category="]');categoryLinks.forEach(link => {link.textContent = categoryName;link.href = `/article?category=${categoryId}`;});}replaceCategory(doc, articleData.category);return true;};let attempts = 0;const interval = setInterval(() => {try {if (performCoreReplace() || ++attempts >= 50) {clearInterval(interval);if (!performCoreReplace()) {showError('页面结构加载超时', articleId, 'article');return;}const doc = iframe.contentDocument || iframe.contentWindow.document;setupLinkInterceptor(doc);addMdBlockToggle(doc);addShikiCopyButtons(doc);const actionObserver = new MutationObserver(() => {hijackActionButtons(doc, articleData, articleId);});actionObserver.observe(doc.body, { childList: true, subtree: true });doc.addEventListener('click', function(e) {const editorLink = e.target.closest('a[data-lgs-editor]');if (!editorLink) return;if (editorLink.hasAttribute('data-lgs-disabled')) {e.preventDefault();e.stopPropagation();return;}e.preventDefault();e.stopPropagation();editorLink.setAttribute('data-lgs-disabled', 'true');triggerWorkflowWithLogin(editorLink, articleId, 'article');}, true);setupSourceObserver(doc, articleData.content);document.getElementById('lgsinlg-loading').style.display = 'none';iframe.style.display = '';window.__LGSinLG_active = true;console.log('[LGSinLG] 文章接管完成');setupComments(doc, articleId);}} catch (e) {clearInterval(interval);console.error('[LGSinLG] 文章轮询异常', e);handleAutoRefresh(e);}}, 200);function setupSourceObserver(doc, rawContent) {const TARGET_SELECTOR = '.card.padding-default .code-card-top pre';const PROCESSED_ATTR = 'data-lgs-processed';const initialPre = doc.querySelector(TARGET_SELECTOR);if (initialPre && !initialPre.hasAttribute(PROCESSED_ATTR)) {const innerDiv = initialPre.querySelector('div');if (innerDiv) innerDiv.textContent = rawContent;else initialPre.textContent = rawContent;initialPre.setAttribute(PROCESSED_ATTR, 'true');}const observer = new MutationObserver(() => {const pre = doc.querySelector(TARGET_SELECTOR);if (pre && !pre.hasAttribute(PROCESSED_ATTR)) {const innerDiv = pre.querySelector('div');if (innerDiv) innerDiv.textContent = rawContent;else pre.textContent = rawContent;pre.setAttribute(PROCESSED_ATTR, 'true');}});observer.observe(doc.body, { childList: true, subtree: true });}}).catch(err => {console.error('[LGSinLG] 文章 Promise 异常', err);showError('该文章尚未被保存站收录', articleId, 'article');});}// ---------- 评论区接管 ----------function fetchReplies(articleId, after = null) {let url = `https://www.luogu.com.cn/article/${articleId}/replies`;if (after !== null) url += `?after=${after}`;return fetch(url).then(res => {if (!res.ok) throw new Error(`评论接口 HTTP ${res.status}`);return res.json();}).then(data => data.replySlice || []);}function renderReplyFromTemplate(templateRow, reply, doc) {console.log('[LGSinLG] 渲染评论,原始数据:', reply);const row = templateRow.cloneNode(true);const avatar = row.querySelector('.avatar');if (avatar) avatar.src = `https://cdn.luogu.com.cn/upload/usericon/${reply.author.uid}.png`;const userLink = row.querySelector('.luogu-username a[href^="/user/"]');if (userLink) {userLink.href = `/user/${reply.author.uid}`;userLink.textContent = reply.author.name;userLink.style.color = USER_CONFIG.colorMap[reply.author.color] || '#333';userLink.addEventListener('click', (e) => {e.preventDefault();window.top.location.href = `/user/${reply.author.uid}`;});}const usernameContainer = row.querySelector('.luogu-username');if (usernameContainer) {const existingBadges = usernameContainer.querySelectorAll('a[target="_blank"], .svg-inline--fa.fa-badge-check');existingBadges.forEach(el => {const anchor = el.closest('a');if (anchor) anchor.remove();else el.remove();});}const timeEl = row.querySelector('time');if (timeEl) {const rawTime = reply.time || reply.createdAt || reply.createTime;const isoTime = parseApiTime(rawTime);timeEl.setAttribute('datetime', isoTime || '');timeEl.setAttribute('title', isoTime ? formatTime(isoTime) : '未知');timeEl.textContent = isoTime ? getRelativeTime(isoTime) : '';}const contentDiv = row.querySelector('.content');if (contentDiv) {const content = reply.content || reply.renderedContent || '';contentDiv.textContent = content;contentDiv.style.whiteSpace = 'pre-line';constrainImages(contentDiv);forceExternalLinks(contentDiv);}const deleteLink = row.querySelector('.meta a[href*="javascript:void"]');if (deleteLink) deleteLink.remove();return row;}function setupComments(doc, articleId) {const commentContainer = doc.querySelector('.article-comment');if (!commentContainer || commentContainer.dataset.lgsProcessed) return;commentContainer.dataset.lgsProcessed = 'true';// 禁用排序下拉const sortWrapper = commentContainer.querySelector('.combo-wrapper');if (sortWrapper) {sortWrapper.style.pointerEvents = 'none';sortWrapper.style.opacity = '0.5';sortWrapper.title = '评论区已接管,排序不可用';}// 禁用评论输入区域const textarea = commentContainer.querySelector('textarea');if (textarea) {const replyForm = textarea.closest('.l-card')|| textarea.closest('form')|| textarea.closest('.reply-box')|| textarea.closest('.comment-editor');if (replyForm) {replyForm.style.pointerEvents = 'none';replyForm.style.opacity = '0.5';replyForm.title = '评论区已由脚本接管,暂不支持发表';}}// 尝试移除原生加载更多(可能此时还未渲染)const nativeLoadMoreLink = commentContainer.querySelector('p[style*="text-align: center"] a[href="javascript:void 0"]');if (nativeLoadMoreLink && nativeLoadMoreLink.parentElement) {nativeLoadMoreLink.parentElement.remove();}const rowWrap = commentContainer.querySelector('.row-wrap');if (!rowWrap) return;const doInit = (templateRow) => {rowWrap.innerHTML = '';const countSpan = commentContainer.querySelector('.comment-filter-line span[style*="flex"]');if (countSpan) countSpan.textContent = '已加载 0 条评论';let allReplies = [];let lastId = null;let isLoading = false;function updateCount() {if (countSpan) countSpan.textContent = `已加载 ${allReplies.length} 条评论`;}function appendReplies(replies) {replies.forEach(reply => {const el = renderReplyFromTemplate(templateRow, reply, doc);rowWrap.appendChild(el);allReplies.push(reply);});if (replies.length > 0) lastId = replies[replies.length - 1].id;updateCount();loadMoreBtn.style.display = replies.length === 0 ? 'none' : 'inline';}async function loadNextPage() {if (isLoading) return;isLoading = true;loadMoreBtn.textContent = '加载中…';try {const replies = await fetchReplies(articleId, lastId);appendReplies(replies);if (replies.length === 0) loadMoreBtn.style.display = 'none';else loadMoreBtn.textContent = '加载更多';} catch (e) {console.error('[LGSinLG] 加载评论失败', e);loadMoreBtn.textContent = '加载失败,点击重试';loadMoreBtn.style.display = 'inline';} finally {isLoading = false;}}function refreshComments() {rowWrap.innerHTML = '';allReplies = [];lastId = null;updateCount();loadMoreBtn.style.display = 'none';isLoading = false;fetchReplies(articleId).then(replies => {appendReplies(replies);}).catch(err => {console.error('[LGSinLG] 刷新评论失败', err);if (countSpan) countSpan.textContent = '评论加载失败';});}let loadMoreBtn = doc.getElementById('lgs-load-more');if (!loadMoreBtn) {loadMoreBtn = doc.createElement('button');loadMoreBtn.id = 'lgs-load-more';loadMoreBtn.textContent = '加载更多';loadMoreBtn.style.display = 'none';loadMoreBtn.addEventListener('click', loadNextPage);loadMoreBtn.style.border = 'none';loadMoreBtn.style.backgroundColor = 'rgba(0, 0, 0, 0)';loadMoreBtn.style.color = 'rgb(52, 152, 219)';loadMoreBtn.style.cursor = 'pointer';loadMoreBtn.style.fontFamily = '-apple-system, "system-ui", "Helvetica Neue", "PingFang SC", "Noto Sans", "Noto Sans SC", "Source Sans Pro", "Source Han Sans", "Segoe UI", Arial, "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif';loadMoreBtn.style.fontSize = '16px';loadMoreBtn.style.height = 'auto';loadMoreBtn.style.lineHeight = '24px';loadMoreBtn.style.textAlign = 'center';loadMoreBtn.style.textDecoration = 'none';loadMoreBtn.style.width = 'auto';const wrapper = doc.createElement('p');wrapper.style.textAlign = 'center';wrapper.style.margin = '0';wrapper.appendChild(loadMoreBtn);commentContainer.appendChild(wrapper);}fetchReplies(articleId).then(replies => {appendReplies(replies);}).catch(err => {console.error('[LGSinLG] 初始评论加载失败', err);if (countSpan) countSpan.textContent = '评论加载失败,点击刷新重试';});// 持续监听并移除后出现的原生“加载更多”按钮const nativeCleaner = new MutationObserver(() => {const nativeLink = commentContainer.querySelector('p[style*="text-align: center"] a[href="javascript:void 0"]');if (nativeLink && nativeLink.parentElement) {console.log('[LGSinLG] 移除后出现的原生加载更多按钮');nativeLink.parentElement.remove();}});nativeCleaner.observe(commentContainer, { childList: true, subtree: true });};const templateRow = rowWrap.querySelector('.row');if (templateRow) {doInit(templateRow);return;}const observer = new MutationObserver((mutations, obs) => {const row = rowWrap.querySelector('.row');if (row) {obs.disconnect();doInit(row);}});observer.observe(rowWrap, { childList: true, subtree: true });}// ---------- 其他接管辅助函数 ----------function hijackActionButtons(doc, articleData, articleId) {const MARKER_EDIT = 'data-lgs-editor';const MARKER_LIKE = 'data-lgs-like';const MARKER_FAV = 'data-lgs-fav';const MARKER_DISLIKE = 'data-lgs-dislike';const actionDivs = doc.querySelectorAll('.actions');actionDivs.forEach(actionsDiv => {const allButtons = actionsDiv.querySelectorAll('.button-2line');allButtons.forEach(btn => {const rawText = (btn.querySelector('.text') || btn).textContent.trim();if (rawText === '收藏' && !btn.hasAttribute(MARKER_FAV)) {const count = articleData.favorCount || 0;const textSpan = btn.querySelector('.text');if (textSpan) textSpan.textContent = count;else btn.textContent = count;btn.style.pointerEvents = 'none';btn.style.opacity = '0.7';btn.style.cursor = 'default';const parentLink = btn.closest('a');if (parentLink) {parentLink.removeAttribute('href');parentLink.style.pointerEvents = 'none';}btn.setAttribute(MARKER_FAV, 'true');} else if (rawText === '点赞' && !btn.hasAttribute(MARKER_LIKE)) {const count = articleData.upvote || 0;const textSpan = btn.querySelector('.text');if (textSpan) textSpan.textContent = count;else btn.textContent = count;btn.style.pointerEvents = 'none';btn.style.opacity = '0.7';btn.style.cursor = 'default';const parentLink = btn.closest('a');if (parentLink) {parentLink.removeAttribute('href');parentLink.style.pointerEvents = 'none';}btn.setAttribute(MARKER_LIKE, 'true');} else if (rawText.startsWith('不推荐') && !btn.hasAttribute(MARKER_DISLIKE)) {btn.style.pointerEvents = 'none';btn.style.opacity = '0.7';btn.style.cursor = 'default';const parentLink = btn.closest('a');if (parentLink) {parentLink.removeAttribute('href');parentLink.style.pointerEvents = 'none';}btn.setAttribute(MARKER_DISLIKE, 'true');}});const editLinks = actionsDiv.querySelectorAll('a[href*="/edit"]');editLinks.forEach(link => {if (link.hasAttribute(MARKER_EDIT)) return;link.removeAttribute('href');const textSpan = link.querySelector('.text');if (textSpan) textSpan.textContent = ' 更新 ';link.setAttribute(MARKER_EDIT, 'true');});});}function handleAutoRefresh(error) {console.error('[LGSinLG] handleAutoRefresh:', error && error.message);if (error && error.message && (error.message.includes('cross-origin') || error.message.includes('Blocked a frame'))) {console.warn('[LGSinLG] 跨域错误,刷新页面');location.reload();} else {console.warn('[LGSinLG] 非跨域错误,清理 iframe');const ifr = document.getElementById('lgsinlg-article-iframe') || document.getElementById('lgsinlg-paste-iframe');if (ifr) ifr.remove();if (document.getElementById('lgsinlg-article-iframe')) window.__LGSinLG_article_handled = false;if (document.getElementById('lgsinlg-paste-iframe')) window.__LGSinLG_paste_handled = false;window.__LGSinLG_active = false;}}// ---------- 工作流与认证 ----------function getStoredToken() { return GM_getValue('lgs_token', ''); }function triggerWorkflowWithLogin(btn, targetId, type, onSuccess) {if (btn.disabled || btn.style.pointerEvents === 'none') return;const storedToken = getStoredToken();if (storedToken) {executeWorkflow(btn, targetId, type, storedToken, onSuccess);return;}setButtonState(btn, '登录中...');const authWindow = window.open('https://api.luogu.me/auth/cp/login', 'lgs-login', 'width=600,height=700');if (!authWindow) {alert('请允许弹出窗口以完成登录');resetButtonState(btn, '更新');return;}let pollCount = 0;const maxPoll = 240;const pollTimer = setInterval(() => {const token = getStoredToken();if (token) {clearInterval(pollTimer);authWindow.close();executeWorkflow(btn, targetId, type, token, onSuccess);} else if (authWindow.closed || ++pollCount > maxPoll) {clearInterval(pollTimer);resetButtonState(btn, '更新');}}, 500);}function executeWorkflow(btn, targetId, type, token, onSuccess) {setButtonState(btn, '发送中...');const workflowName = type === 'article' ? 'article-save-pipeline' : 'paste-save-pipeline';GM_xmlhttpRequest({method: 'POST',url: `https://api.luogu.me/workflow/create/template/${workflowName}`,headers: {'Content-Type': 'application/json','Authorization': `Bearer ${token}`},data: JSON.stringify({ targetId }),onload: function(res) {try {const data = JSON.parse(res.responseText);if (data.code === 200) {resetButtonState(btn, '更新');if (typeof onSuccess === 'function') onSuccess();} else {if (data.code === 401) {GM_setValue('lgs_token', '');alert('登录已过期,请重新点击按钮登录');} else {alert('工作流启动失败:' + (data.message || '未知错误'));}resetButtonState(btn, '更新');}} catch (e) {alert('响应解析失败');resetButtonState(btn, '更新');}},onerror: function(err) {console.error('[LGSinLG] 网络错误', err);alert('网络错误,请稍后重试');resetButtonState(btn, '更新');}});}function setButtonState(btn, text) {const textSpan = btn.querySelector && btn.querySelector('.text');if (textSpan) textSpan.textContent = ` ${text} `;else btn.textContent = text;if (btn.tagName === 'BUTTON') btn.disabled = true;else btn.style.pointerEvents = 'none';}function resetButtonState(btn, text) {const textSpan = btn.querySelector && btn.querySelector('.text');if (textSpan) textSpan.textContent = ` ${text} `;else btn.textContent = text;if (btn.tagName === 'BUTTON') btn.disabled = false;else btn.style.pointerEvents = '';btn.removeAttribute('data-lgs-disabled');}function handleOAuthCallback() {if (!location.pathname.startsWith('/auth/callback') || !window.opener) return;document.body.innerHTML = '<div style="text-align:center; padding:50px;">正在完成登录...</div>';const params = new URLSearchParams(location.search);const token = params.get('token');if (token) {GM_setValue('lgs_token', token);document.body.innerHTML = '<div style="text-align:center; padding:50px;">登录成功!窗口即将关闭...</div>';setTimeout(() => window.close(), 1500);} else {document.body.innerHTML = '<div style="text-align:center; padding:50px;">登录失败,未获取到 Token,请关闭此窗口后重试。</div>';}}// ---------- 路由与生命周期 ----------function cleanupTakeover() {console.log('[LGSinLG] 执行接管清理');if (waitForSecurityTimer) {clearTimeout(waitForSecurityTimer);waitForSecurityTimer = null;}window.__LGSinLG_active = false;window.__LGSinLG_paste_handled = false;window.__LGSinLG_article_handled = false;['lgsinlg-paste-iframe', 'lgsinlg-article-iframe'].forEach(id => {const el = document.getElementById(id);if (el) el.remove();});const loading = document.getElementById('lgsinlg-loading');if (loading) loading.remove();const error = document.getElementById('lgsinlg-error');if (error) error.remove();}let currentPath = location.pathname;let pending = false;let waitForSecurityTimer = null;function recoverActiveIfNeeded() {const pasteIfr = document.getElementById('lgsinlg-paste-iframe');const articleIfr = document.getElementById('lgsinlg-article-iframe');if ((pasteIfr || articleIfr) && !window.__LGSinLG_active) {window.__LGSinLG_active = true;if (waitForSecurityTimer) {clearTimeout(waitForSecurityTimer);waitForSecurityTimer = null;}}}function isSecurityPage() {const warningTitle = document.querySelector('body > div:nth-child(1) > div > h3');return document.title === '安全访问中心 - 洛谷' && warningTitle && warningTitle.textContent.trim() === '即将离开洛谷';}function processRoute() {recoverActiveIfNeeded();console.log('[LGSinLG] processRoute active:', window.__LGSinLG_active, 'path:', location.pathname);if (window.__LGSinLG_active) {const currentPasteId = getPasteIdFromUrl();const currentArticleId = getArticleIdFromUrl();if ((currentPasteId && window.__LGSinLG_paste_handled) || (currentArticleId && window.__LGSinLG_article_handled)) {console.log('[LGSinLG] 仍在接管页面,忽略路由变化');return;}console.log('[LGSinLG] 接管已失效,清理并刷新');cleanupTakeover();location.reload();return;}if (location.hostname.endsWith('.luogu.me') || location.hostname === 'luogu.me') {if (location.pathname.startsWith('/auth/callback')) {handleOAuthCallback();} else {console.log('[LGSinLG] luogu.me 非回调页面,放行');}return;}if (waitForSecurityTimer) {clearTimeout(waitForSecurityTimer);waitForSecurityTimer = null;}const pasteId = getPasteIdFromUrl();const articleId = getArticleIdFromUrl();if (pasteId) {console.log('[LGSinLG] 粘贴页 pasteId:', pasteId);if (isSecurityPage()) {handlePastePage(pasteId);return;}waitForSecurity(pasteId, 'paste');return;}if (articleId) {console.log('[LGSinLG] 文章页 articleId:', articleId);if (isSecurityPage()) {handleArticlePage(articleId);return;}waitForSecurity(articleId, 'article');return;}const uid = getUserIdFromUrl();if (uid) {const loginUid = getLoginUid();if (loginUid && loginUid === uid) {console.log('[LGSinLG] 自己的主页,跳过卡片');removeUserCardIfExists();return;}// 等待侧边栏容器就绪,否则稍后再试if (!document.querySelector('.sidebar-container > .main')) {setTimeout(() => processRoute(), 300);return;}fetchAndUpdateCard(uid);return;}console.log('[LGSinLG] 未匹配接管规则,清理遗留 iframe');removeUserCardIfExists();const pasteIfr = document.getElementById('lgsinlg-paste-iframe');if (pasteIfr) pasteIfr.remove();const articleIfr = document.getElementById('lgsinlg-article-iframe');if (articleIfr) articleIfr.remove();window.__LGSinLG_paste_handled = false;window.__LGSinLG_article_handled = false;window.__LGSinLG_active = false;}function waitForSecurity(id, type) {let attempts = 0;const maxAttempts = 100;const check = () => {if (isSecurityPage()) {console.log(`[LGSinLG] 安全页就绪,接管 ${type} ${id}`);if (type === 'paste') handlePastePage(id);else handleArticlePage(id);return;}if (++attempts < maxAttempts) {waitForSecurityTimer = setTimeout(check, 200);} else {console.warn(`[LGSinLG] 安全页等待超时,放弃接管`);waitForSecurityTimer = null;window.__LGSinLG_paste_handled = false;window.__LGSinLG_article_handled = false;window.__LGSinLG_active = false;}};check();}const observer = new MutationObserver(() => {if (pending || window.__LGSinLG_active) return;const newPath = location.pathname;if (newPath !== currentPath) {console.log('[LGSinLG] 路径变化:', currentPath, '->', newPath);currentPath = newPath;pending = true;requestAnimationFrame(() => {processRoute();pending = false;});}});const app = document.querySelector('.main-container');if (app) observer.observe(app, { childList: true, subtree: true });else observer.observe(document.body, { childList: true, subtree: true });window.addEventListener('popstate', () => {console.log('[LGSinLG] popstate 触发,新路径:', location.pathname);const errorDiv = document.getElementById('lgsinlg-error');if (errorDiv && errorDiv.style.display !== 'none') {location.reload();return;}currentPath = location.pathname;processRoute();});if (getPasteIdFromUrl() || getArticleIdFromUrl() || (location.hostname.endsWith('.luogu.me') && location.pathname.startsWith('/auth/callback'))) {processRoute();} else {let initTimer = setInterval(() => {const container = document.querySelector('.sidebar-container > .main, .full-container, main');if (container) {clearInterval(initTimer);processRoute();}}, 200);}})();```::::最后在脚本的 USER_CONFIG 内设置 templatePasteId 为你刚刚创建的剪贴板的 ID ,templateArticleId 为你刚刚创建的文章 ID ,ID 就是地址栏最后那一串字符,如果模版 ID 无法访问,通常会提示页面结构加载超时。# 注意事项受限于 API 限制以及其他原因,一些功能不方便实现,比如用户牌子,徽章,文章目录联动,发布评论等,并且由于是第三方渲染的 Markdown ,一些洛谷 Markdown 特性无法渲染出来。并且脚本依赖于洛谷的前端命名,如果未来更新了,脚本可能会失效。剪切板和文章不能删除,否则会导致功能异常。因为仅对页面表面文字进行了替换,一些依赖于页面信息的脚本如 copy-markdown 将无法正确获取文章的 Markdown 。# 结语欢迎大家使用,如果有 BUG 请在评论区反馈。123456789101112131415161716 行未改动343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778:::warning[本文技术已经过时]{open}本方案已经过时,建议寻找其他脚本。:::# 背景众所周知,洛谷分为国内站和国际站,而国内站只能查看自己的剪贴板和自己的文章,以及全站推荐的文章,而个人主页更是在最近的更新里改成了仅国际站可见。这时候我们便可以使用[洛谷保存站](https://www.luogu.me/),下文简称保存站。::::info[什么是洛谷保存站?]洛谷保存站是一个由 [Federico2903](https://www.luogu.com.cn/user/381949) 运营的第三方网站,可以实现保存洛谷的剪贴板、用户主页、文章等,并且不会因地区限制而访问失败。::::之前也有过检测到无法访问就跳转到保存站的脚本,但是无一例外都必须要去访问保存站才能查看,而保存站终究还是第三方网站,界面和洛谷大相径庭,在查找资料时需要多次跳转,容易打断思路,而且也无法快速跳转到洛谷相关页面。于是我和 DeepSeek 制作了这个脚本,能够通过 [保存站 API](https://api.luogu.me)([文档](https://luogu-saver-next.apifox.cn/))以及洛谷官方 API 获取用户、文章、剪贴板信息,嵌入到洛谷当中。# 功能- 非自己、管理员的主页从保存站获取个人简介并追加卡片。16 行未改动# 原理## 个人简介通过 API 获取个人简介 Markdown 渲染后的 HTML,然后追加一个卡片,将获取到的 HTML 嵌入。## 剪贴板访问一篇无法访问的剪贴板时,会提示安全访问中心,是否要跳转到 `www.luogu.com/xxx` ,检测到这个页面后,脚本会在页面上覆盖一个全屏 iframe 访问模版剪贴板,之所以用 iframe 是为了尽可能实现原生体验,实现 1:1 还原洛谷界面,并且能够实现地址栏不动,然后通过动态检测替换掉模版内容,并创建一个更新按钮。## 专栏大部分原理同剪贴板,但是需要做的事更多了,因为右侧的目录并不会自动生成,所以脚本会先遍历文章,然后在右侧创建目录,但是会从模版的目录里提取出相关 CSS 然后使用。并且还会将操作栏的点赞、收藏、不推荐修改为不可点击,并替换文本为保存站的点赞数。然后通过洛谷官方 API 获得评论信息并追加。# 使用受限于原理限制,需要手动创建一个可以正常访问的剪贴板和文章,剪贴板没有特殊要求,但文章需要有三级标题,比如```markdown# 1## 2### 3```然后在专栏中发一个评论,并确保点赞数和收藏数为 0(可以设置为私有)。然后在浏览器中安装 Tampermonkey。访问安装链接,然后点击安装,如果提示你需要安装 ScriptCat 点击下方的已经安装,继续安装,然后会弹出 Tampermonkey 的安装页面,点击安装即可。刷新原有页面即可生效。部分浏览器需要在插件设置里给 Tampermonkey 开启“允许用户脚本”权限。[从 ScriptCat 安装](https://scriptcat.org/zh-CN/script-show-page/6736)最后点击 Tampermonkey 图标,打开管理面板,点击本脚本的编辑按钮,在脚本的 USER_CONFIG 内设置 templatePasteId 为你刚刚创建的剪贴板的 ID,templateArticleId 为你刚刚创建的文章 ID,ID 就是地址栏最后那一串字符,如果模版 ID 无法访问,通常会提示页面结构加载超时。# 注意事项因为实现比较复杂,用户徽章会和悬浮菜单去除了。由于是第三方渲染的 Markdown,一些洛谷 Markdown 特性无法渲染出来。并且脚本依赖于洛谷的前端命名,如果未来更新了,脚本可能会失效。模版剪切板和文章不能删除,否则会导致功能异常。因为仅对页面表面文字进行了替换,一些依赖于页面信息的脚本如 copy-markdown 将无法正确获取文章的 Markdown。# 结语欢迎大家使用,如果有 BUG 请在 ScriptCat 中反馈,本页面可能无法及时更新,建议在 ScriptCat 中查看。