版本比较
在洛谷内无缝访问所有文章
正文
增加 365 行删除 205 行
16 行未改动17181920212122232425262727282930315 行未改动3738394041414243444546474849505152535455565758596060616162636465663 行未改动7071727373747576777829 行未改动1081091101111111121131131141151161176 行未改动12412512612712812912812913013110 行未改动14214314414514814914614714814910 行未改动1601611621631681691641651661731671681691701711721731741751831841851861871881891901911921931941951761771781791801811821831841851861872041881891901911921932102112122132142152162172181941951961971981993 行未改动2032042052062302072082092102342352112122132142402412152162172182462472192202212222522532232242252262582592272282292302312652662322332342357 行未改动24324424524628228324724824925020 行未改动2712722732742752762772782795 行未改动28528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033118 行未改动350351352353359354355356357363358359360361362368369370371372373374375376377378379380381382383363364365366367368369370392371372373374375398399400376377378403379380381382408409383384385412413414386387388389390391392421393394395396397427398399400401432402403404405406438439440441442443444445446447448449450451452453407408409410411412413414415416417418419420421454455422423424425426427428429430431432116 行未改动全部展开54955055155255355458755555655755855956056156256356456556656756856957057159159257257357457557619 行未改动59659759859962060060160260360460560662860760860961024 行未改动63563663763863964064164264352 行未改动6966976986997007017227237247257027037047055 行未改动71171271371473971571671771814 行未改动7337347357367627637647377387397407418 行未改动7507517527537817547557567573 行未改动76176276376476576676776876977077177277323 行未改动79779879980082480180280380410 行未改动81581681781884381982082182282382484982582682782882983085585685785885983183283383412 行未改动8478488498508518528818828838848538548558564 行未改动86186286386489786586686786814 行未改动8838848858869209219228878888898908919 行未改动9019029039049409059069079089099109119129139509519529539549149159169179189199209219229239249259649659669679269279289299302 行未改动93393493593697893798093893994094194271 行未改动1014101510161017106010181019102010215 行未改动102710281029103010741031103210771078107910801081103310341035103613 行未改动1050105110521053110310541055105610571058105910604 行未改动10651066106710681116106910701071107210731074107510761122107710781079108010811082108310841128112911301131113210851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131854 行未改动1373137413751376120212031204120512061207120812091377137813791380138112121382138313841385138613871388138913901391139213931394139529 行未改动14251426142714281258142914301431143214331434143514362 行未改动143914401441144212691443144414451446144712 行未改动14601461146214631290129112921293129414641465146614671468146914701471130113021303130413051472147314741475147614771478147913121313148014811482148314844 行未改动14891490149114921493149414951496149714981499150015011502133513361503150415051506150724 行未改动15321533153415351369153615371538153913731374154015411542154313781544154515461547154815491550138515511552155315545 行未改动1560156115621563139915641565140115661567156814051569157015711572141015731574141215751576157714161578157915801581158214221583142415841426158515861587158815891590159115921593159415951433159615971598159916007 行未改动160816091610161114491612161316141615161616171618161914571620162116221623162422 行未改动1647164816491650148816511652165316541655165616571658149716591660166116621663150316641665166616675 行未改动16731674167516761517167716781679168016814 行未改动16 行未改动
# 截图
个人专栏
个人主页
剪贴板
# 原理
## 个人简介5 行未改动访问一篇无法访问的剪贴板时,会提示安全访问中心,是否要跳转到 www.luogu.com/xxx ,检测到这个页面后,脚本会在页面上覆盖一个全屏 iframe 访问模版剪贴板,之所以用 iframe 是为了尽可能实现原生体验,实现 1:1 还原洛谷界面,并且能够实现地址栏不动,然后通过动态检测替换掉模版内容,并创建一个更新按钮。
## 专栏
大部分原理同剪贴板,但是需要做的事更多了,因为右侧的目录并不会自动生成,所以脚本会先遍历文章,然后在右侧创建目录,但是会从模版的目录里提取出相关 CSS 然后使用。并且还会将操作栏的点赞、收藏、不推荐修改为不可点击,并替换文本为保存站的点赞数。然后删除评论区。大部分原理同剪贴板,但是需要做的事更多了,因为右侧的目录并不会自动生成,所以脚本会先遍历文章,然后在右侧创建目录,但是会从模版的目录里提取出相关 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.7// @description 洛谷国内站:用户主页添加个人介绍卡片;陌生剪切板/文章通过 iframe + API 替换内容,支持 CP OAuth 自动登录和工作流更新;修复多实例刷新问题;替换文章分类、点赞收藏数(纯数字)并禁止交互;支持多操作栏;动态替换右侧目录(保留原生样式);修复加载卡死和跨域自动刷新;iframe 内非锚点链接在顶层跳转;修复 heading-anchor 锚点;安全页超时放弃接管,不再刷新;修改页面标题格式;头像链接放行保留抽屉菜单;修复时间显示为本地时间;使用全局事件委托彻底解决编辑按钮跳转;主页更新按钮宽度自适应;恢复点赞收藏数及禁用交互功能;检测自己主页不再追加个人介绍卡片;修复浏览器返回后页面不更新的问题;修复 getLoginUid 选择器以适配新版导航栏;修复未保存文章/剪切板时页面卡死在加载中,增加“保存”按钮,修复后退与重试;修复图片宽度溢出问题;注入 Shiki 代码块专用样式,完美显示代码高亮、行号,不影响侧边栏及其他区域;添加 md-block 折叠展开(按钮位于标题最右侧);代码块复制按钮;修复 md-block 标题图标与文字重叠// @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_xmlhttpRequest3 行未改动
(function() { 'use strict';
console.log('[LGSinLG] 脚本启动,版本 1.0.7', new Date().toISOString()); 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);29 行未改动 8: '闲话' } };
// Shiki 代码块专用样式(不影响页面其它区域) // Shiki 代码块专用样式 const SHIKI_CSS = ` /* 激活 Shiki 内联颜色变量 */ .shiki, .shiki span { color: var(--shiki-light, #24292e); } .shiki {6 行未改动 .shiki { background-color: var(--shiki-dark-bg, #0d1117); } }
/* 代码块容器外观 */ pre.shiki { padding: 16px; border-radius: 8px; border: 1px solid #d0d7de;10 行未改动 background-color: #0d1117 !important; border-color: #30363d; } }
/* 行号(纯 CSS 实现) */ .shiki { counter-reset: line; } .shiki .line::before {10 行未改动 .shiki .line::before { color: #484f58; } }
/* 行内高亮 */ .code-line.highlight { background: rgba(255, 229, 100, 0.25); } /* 自定义容器(md-block) */ .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.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; /* 为左侧图标预留空间,防止重叠 */ 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; }
/* 标题前的图标(绝对定位,不占用 flex 空间) */ .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;3 行未改动 mask-repeat: no-repeat; -webkit-mask-size: contain; mask-size: contain; position: absolute; left: 0.2em; /* 微调位置,与左边框对齐 */ 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>'); }
/* 信息(蓝色 i 图标) */ .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; }7 行未改动 } .toggle-icon.collapsed { transform: rotate(-90deg); }
/* === 代码块复制按钮样式 === */ .shiki-wrapper { position: relative; } .shiki-copy-btn {20 行未改动 } } `;
// ---------- 工具函数 ---------- function getUserIdFromUrl() { const m = location.pathname.match(/^\/user\/(\d+)\/?$/); return m ? m[1] : null; }5 行未改动 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 => {18 行未改动 }
function createClickableUsername(name, color, userId) { const span = document.createElement('span'); span.style.cssText = `font-weight: bold; color: ${color}; cursor: pointer; text-decoration: underline;`; span.style.cssText = `font-weight: bold; color: ${color}; cursor: pointer;`; span.textContent = name; span.addEventListener('click', function(e) { e.preventDefault(); window.open(`/user/${userId}`, '_blank'); window.top.location.href = `/user/${userId}`; }); return span; }
function removeComments(doc) { const commentSelector = '.article-comment'; const remove = () => { const el = doc.querySelector(commentSelector); if (el) el.remove(); }; remove(); let attempts = 0; const maxAttempts = 10; const timer = setInterval(() => { if (doc.querySelector(commentSelector)) remove(); if (++attempts >= maxAttempts) clearInterval(timer); }, 300); }
// 注入 Shiki 专用样式到 iframe 的 <head> 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 代码块样式已注入'); }
// === 新增:md-block 折叠/展开功能(按钮位于标题最右侧) === 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) return; if (title.dataset.toggleBound) return;
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);
const toggle = () => { title.addEventListener('click', () => { const collapsed = icon.classList.toggle('collapsed'); body.style.display = collapsed ? 'none' : ''; };
title.addEventListener('click', toggle); }); title.style.cursor = 'pointer'; title.dataset.toggleBound = 'true'; }); console.log('[LGSinLG] md-block 折叠功能已激活'); }
// === 新增:代码块复制按钮 === function addShikiCopyButtons(doc) { if (!doc || !doc.body) return; const shikiBlocks = doc.querySelectorAll('pre.shiki'); shikiBlocks.forEach(pre => { if (pre.parentElement && pre.parentElement.classList.contains('shiki-wrapper')) return;
const wrapper = doc.createElement('div'); wrapper.className = 'shiki-wrapper'; pre.parentNode.insertBefore(wrapper, pre); wrapper.appendChild(pre);
const btn = doc.createElement('button'); btn.className = 'shiki-copy-btn'; btn.textContent = '复制'; btn.addEventListener('click', () => { const code = pre.textContent || ''; const copy = (text) => { navigator.clipboard.writeText(text).then(() => { btn.textContent = '已复制'; setTimeout(() => { btn.textContent = '复制'; }, 2000); }).catch(() => { const ta = doc.createElement('textarea'); ta.value = text; 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); }); 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); }); }; copy(code); }); wrapper.appendChild(btn); }); console.log('[LGSinLG] 代码块复制按钮已添加'); }
// ---------- 个人介绍卡片 ---------- const CARD_ID = 'lgsinlg-intro-card';
function isAdminUser() { const rows = document.querySelectorAll('.l-flex-info-row');116 行未改动全部展开 }
function fetchAndUpdateCard(uid) { if (isAdminUser()) { removeUserCardIfExists(); return; }
const elements = getOrCreateCard(uid); if (!elements) return; if (!elements) { // 容器尚未就绪,延迟 300ms 后重试(最多尝试 10 次) 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/${uid}`, headers: { 'User-Agent': 'Uptime-Kuma' }, url: `https://api.luogu.me/user/query/${uid}`, onload: function(res) { try { const data = JSON.parse(res.responseText); if (data.code === 200 && data.data) {19 行未改动 btn.disabled = true; GM_xmlhttpRequest({ method: 'POST', url: `https://api.luogu.me/user/${uid}/refresh`, headers: { 'User-Agent': 'Uptime-Kuma' }, onload: function(res) { try { const data = JSON.parse(res.responseText); if (data.code === 200) { GM_xmlhttpRequest({ method: 'GET', url: `https://api.luogu.me/user/${uid}`, headers: { 'User-Agent': 'Uptime-Kuma' }, onload: function(resp) { try { const p = JSON.parse(resp.responseText); if (p.code === 200 && p.data) {24 行未改动 } }); }
// ---------- 接管流程公共部分 ---------- function waitForIframeLoad(iframe, timeoutMs = 20000) { return new Promise((resolve, reject) => { const timer = setTimeout(() => { console.warn('[LGSinLG] iframe 加载超时');52 行未改动 <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());
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;';5 行未改动 const apiPromise = new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: 'GET', url: `https://api.luogu.me/paste/query/${pasteId}`, headers: { 'User-Agent': 'Uptime-Kuma' }, onload(res) { try { const data = JSON.parse(res.responseText); if (data.code === 200 && data.data) resolve(data.data);14 行未改动 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(); }); triggerWorkflowWithLogin(saveBtn, id, type, () => location.reload()); }); document.getElementById('lgsinlg-error').appendChild(saveBtn); const ifr = document.getElementById('lgsinlg-paste-iframe'); if (ifr) ifr.remove();8 行未改动 let doc; try { doc = iframe.contentDocument || iframe.contentWindow.document; } catch (e) { console.error('[LGSinLG] 剪切板跨域异常', e); handleAutoRefresh(e); return false; } if (!doc) return false;3 行未改动 if (!markedDiv || !timeCaption || !actionsDiv) return false; markedDiv.innerHTML = pasteData.renderedContent || '<p>暂无内容</p>'; constrainImages(markedDiv); forceExternalLinks(markedDiv); // 移除所有内部锚点链接(href 以 # 开头) const internalAnchors = markedDiv.querySelectorAll('a[href^="#"]'); internalAnchors.forEach(a => { a.replaceWith(document.createTextNode(a.textContent)); }); injectShikiCSS(doc); const authorCaption = doc.querySelector('.author .lfe-caption.author-margin'); if (authorCaption) { const color = USER_CONFIG.colorMap[pasteData.author.color] || '#000';23 行未改动 } 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 = '';10 行未改动 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)) { replaceSourceContent(initialPre, rawContent); initialPre.textContent = rawContent; initialPre.setAttribute(PROCESSED_ATTR, 'true'); } const observer = new MutationObserver(() => { const pre = doc.querySelector(TARGET_SELECTOR); if (pre && !pre.hasAttribute(PROCESSED_ATTR)) { replaceSourceContent(pre, rawContent); pre.textContent = rawContent; pre.setAttribute(PROCESSED_ATTR, 'true'); } }); observer.observe(doc.body, { childList: true, subtree: true }); } function replaceSourceContent(preElement, content) { const innerDiv = preElement.querySelector('div'); if (innerDiv) innerDiv.textContent = content; else preElement.textContent = content; } }) .catch(err => { console.error('[LGSinLG] 剪切板 Promise 异常', err); showError('该剪切板尚未被保存站收录', pasteId, 'paste');12 行未改动 <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());
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;';4 行未改动 const apiPromise = new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: 'GET', url: `https://api.luogu.me/article/query/${articleId}`, headers: { 'User-Agent': 'Uptime-Kuma' }, onload(res) { try { const data = JSON.parse(res.responseText); if (data.code === 200 && data.data) resolve(data.data);14 行未改动 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(); }); triggerWorkflowWithLogin(saveBtn, id, type, () => location.reload()); }); document.getElementById('lgsinlg-error').appendChild(saveBtn); const ifr = document.getElementById('lgsinlg-article-iframe'); if (ifr) ifr.remove();9 行未改动 let doc; try { doc = iframe.contentDocument || iframe.contentWindow.document; } catch (e) { console.error('[LGSinLG] 文章跨域异常', 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('.content-card-top .lfe-caption') || doc.querySelector('.time') || doc.querySelector('time') || doc.querySelector('[datetime]'); if (!timeCaption) { const meta = doc.querySelector('.article-meta') || doc.querySelector('header'); if (meta) timeCaption = meta.querySelector('time') || meta.querySelector('[datetime]'); } 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); 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) => { const newId = `lgs-toc-${index}`; heading.id = newId; const anchorLink = heading.querySelector('a.heading-anchor'); if (anchorLink) anchorLink.href = `#${newId}`; heading.id = `lgs-toc-${index}`; }); const tocContainer = doc.querySelector('.toc'); if (tocContainer) { const tocUl = tocContainer.querySelector('ul');2 行未改动 const templateSpan = templateLi ? templateLi.querySelector('span') : null; tocUl.innerHTML = ''; if (headings.length > 0 && templateLi) { headings.forEach((heading, index) => { const level = parseInt(heading.tagName.charAt(1)); const li = templateLi.cloneNode(false); li.className = `title-${level - 1}`; li.className = `title-${parseInt(heading.tagName.charAt(1)) - 1}`; li.title = heading.textContent.trim(); let span; if (templateSpan) { span = templateSpan.cloneNode(false);71 行未改动 link.href = `/article?category=${categoryId}`; }); } replaceCategory(doc, articleData.category); removeComments(doc); return true; }; let attempts = 0; const interval = setInterval(() => {5 行未改动 return; } const doc = iframe.contentDocument || iframe.contentWindow.document; setupLinkInterceptor(doc); // 注入新功能 addMdBlockToggle(doc); addShikiCopyButtons(doc); const commentObserver = new MutationObserver(() => { const comment = doc.querySelector('.article-comment'); if (comment) comment.remove(); }); commentObserver.observe(doc.body, { childList: true, subtree: true }); const actionObserver = new MutationObserver(() => { hijackActionButtons(doc, articleData, articleId); }); actionObserver.observe(doc.body, { childList: true, subtree: true });13 行未改动 setupSourceObserver(doc, articleData.content); document.getElementById('lgsinlg-loading').style.display = 'none'; iframe.style.display = ''; window.__LGSinLG_active = true; console.log('[LGSinLG] 文章接管完成(含点赞收藏及编辑事件委托)'); console.log('[LGSinLG] 文章接管完成'); // 评论区接管 setupComments(doc, articleId); } } catch (e) { clearInterval(interval); console.error('[LGSinLG] 文章轮询异常', e);4 行未改动 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)) { replaceSourceContent(initialPre, rawContent); 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)) { replaceSourceContent(pre, rawContent); 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 }); } function replaceSourceContent(preElement, content) { const innerDiv = preElement.querySelector('div'); if (innerDiv) innerDiv.textContent = content; else preElement.textContent = content; } }) .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 = '评论区已接管,排序不可用'; }
// ---------- 精确禁用评论输入框(通过 textarea 向上查找父容器) ---------- 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;
// 初始化函数(需要 articleId) 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; }
// 否则观察 rowWrap,等待懒加载完成(不设超时) 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';54 行未改动 }); }
function handleAutoRefresh(error) { console.error('[LGSinLG] handleAutoRefresh 被调用'); console.error('[LGSinLG] 错误信息:', error && error.message); console.error('[LGSinLG] 错误对象:', error); console.error('[LGSinLG] 当前 URL:', location.href); if (error && error.stack) console.error('[LGSinLG] 错误堆栈:', error.stack); const msg = error ? (error.message || '') : ''; if (msg.includes('cross-origin') || msg.includes('Blocked a frame')) { console.warn('[LGSinLG] 检测到跨域错误,即将刷新页面'); 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 并重置状态'); 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;29 行未改动 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', 'User-Agent': 'Uptime-Kuma', 'Authorization': `Bearer ${token}` }, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, data: JSON.stringify({ targetId }), onload: function(res) { try { const data = JSON.parse(res.responseText);2 行未改动 if (typeof onSuccess === 'function') onSuccess(); } else { if (data.code === 401) { GM_setValue('lgs_token', ''); alert('登录已过期,请再次点击按钮重新登录'); alert('登录已过期,请重新点击按钮登录'); } else { alert('工作流启动失败:' + (data.message || '未知错误')); } resetButtonState(btn, '更新');12 行未改动 }
function setButtonState(btn, text) { const textSpan = btn.querySelector && btn.querySelector('.text'); if (textSpan) { textSpan.textContent = ` ${text} `; } else { btn.textContent = 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 (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')) return; if (!window.opener) return; 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) {4 行未改动 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; const iframes = ['lgsinlg-paste-iframe', 'lgsinlg-article-iframe']; iframes.forEach(id => { ['lgsinlg-paste-iframe', 'lgsinlg-article-iframe'].forEach(id => { const el = document.getElementById(id); if (el) el.remove(); }); const loading = document.getElementById('lgsinlg-loading');24 行未改动 }
function processRoute() { recoverActiveIfNeeded(); console.log('[LGSinLG] processRoute 开始,active:', window.__LGSinLG_active, 'path:', location.pathname); 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)) { if ((currentPasteId && window.__LGSinLG_paste_handled) || (currentArticleId && window.__LGSinLG_article_handled)) { console.log('[LGSinLG] 仍在接管页面,忽略路由变化'); return; } console.log('[LGSinLG] 接管已失效,清理并刷新页面'); console.log('[LGSinLG] 接管已失效,清理并刷新'); cleanupTakeover(); location.reload(); return; } if (location.hostname.endsWith('.luogu.me') || location.hostname === 'luogu.me') { if (location.pathname.startsWith('/auth/callback')) { console.log('[LGSinLG] 进入 OAuth 回调处理'); handleOAuthCallback(); } else { console.log('[LGSinLG] luogu.me 非回调页面,放行'); }5 行未改动 } const pasteId = getPasteIdFromUrl(); const articleId = getArticleIdFromUrl(); if (pasteId) { console.log('[LGSinLG] 检测到粘贴页 pasteId:', pasteId); console.log('[LGSinLG] 粘贴页 pasteId:', pasteId); if (isSecurityPage()) { console.log('[LGSinLG] 当前为安全页,直接进入粘贴接管'); handlePastePage(pasteId); return; } console.log('[LGSinLG] 开始轮询等待安全页以接管粘贴'); waitForSecurity(pasteId, 'paste'); return; } if (articleId) { console.log('[LGSinLG] 检测到文章页 articleId:', articleId); console.log('[LGSinLG] 文章页 articleId:', articleId); if (isSecurityPage()) { console.log('[LGSinLG] 当前为安全页,直接进入文章接管'); handleArticlePage(articleId); return; } console.log('[LGSinLG] 开始轮询等待安全页以接管文章'); waitForSecurity(articleId, 'article'); return; } const uid = getUserIdFromUrl(); if (uid) { console.log('[LGSinLG] 检测到用户页 uid:', uid); const loginUid = getLoginUid(); console.log('[LGSinLG] loginUid:', loginUid); if (loginUid && loginUid === uid) { console.log('[LGSinLG] 检测到自己的主页,跳过个人介绍卡片'); console.log('[LGSinLG] 自己的主页,跳过卡片'); removeUserCardIfExists(); return; } if (!document.querySelector('.sidebar-container > .main')) { setTimeout(() => processRoute(), 300); return; } fetchAndUpdateCard(uid); return; } console.log('[LGSinLG] 未匹配到任何接管规则,清理可能遗留的 iframe'); console.log('[LGSinLG] 未匹配接管规则,清理遗留 iframe'); removeUserCardIfExists(); const pasteIfr = document.getElementById('lgsinlg-paste-iframe'); if (pasteIfr) pasteIfr.remove(); const articleIfr = document.getElementById('lgsinlg-article-iframe');7 行未改动 let attempts = 0; const maxAttempts = 100; const check = () => { if (isSecurityPage()) { console.log(`[LGSinLG] 安全页已出现,进入接管 (${type}, id=${id})`); 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] 安全页等待超时 (${maxAttempts} 次),放弃接管`); console.warn(`[LGSinLG] 安全页等待超时,放弃接管`); waitForSecurityTimer = null; window.__LGSinLG_paste_handled = false; window.__LGSinLG_article_handled = false; window.__LGSinLG_active = false;22 行未改动 window.addEventListener('popstate', () => { console.log('[LGSinLG] popstate 触发,新路径:', location.pathname); const errorDiv = document.getElementById('lgsinlg-error'); if (errorDiv && errorDiv.style.display !== 'none') { console.log('[LGSinLG] 检测到错误 UI,popstate 时刷新页面'); location.reload(); return; } currentPath = location.pathname; processRoute(); });
if (getPasteIdFromUrl() || getArticleIdFromUrl() || (location.hostname.endsWith('.luogu.me') && location.pathname.startsWith('/auth/callback'))) { console.log('[LGSinLG] 初始路径匹配,立即执行 processRoute'); processRoute(); } else { let initTimer = setInterval(() => { const container = document.querySelector('.sidebar-container > .main, .full-container, main'); if (container) { console.log('[LGSinLG] 页面 DOM 准备完成,执行初始路由'); clearInterval(initTimer); processRoute(); } }, 200);5 行未改动最后在脚本的 USER_CONFIG 内设置 templatePasteId 为你刚刚创建的剪贴板的 ID ,templateArticleId 为你刚刚创建的文章 ID ,ID 就是地址栏最后那一串字符,如果模版 ID 无法访问,通常会提示页面结构加载超时。
# 注意事项
受限于 API 限制以及其他原因,一些功能不方便实现,比如文章评论区显示功能,文章目录联动等,并且由于是第三方渲染的 Markdown ,一些洛谷 Markdown 特性无法渲染出来。并且脚本依赖于洛谷的前端命名,如果未来更新了,脚本可能会失效。受限于 API 限制以及其他原因,一些功能不方便实现,比如用户牌子,徽章,文章目录联动,发布评论等,并且由于是第三方渲染的 Markdown ,一些洛谷 Markdown 特性无法渲染出来。并且脚本依赖于洛谷的前端命名,如果未来更新了,脚本可能会失效。
剪切板和文章不能删除,否则会导致功能异常。
因为仅对页面表面文字进行了替换,一些依赖于页面信息的脚本如 copy-markdown 将无法正确获取文章的 Markdown 。4 行未改动