正文
增加 25 行删除 1174 行
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227# 背景众所周知,洛谷分为国内站和国际站,而国内站只能查看自己的剪贴板和自己的文章,以及全站推荐的文章,而个人主页更是在最近的更新里改成了仅国际站可见。这时候我们便可以使用[洛谷保存站](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 获取个人简介 Markdown 渲染后的 HTML ,然后追加一个卡片,将获取到的 HTML 嵌入。## 剪贴板访问一篇无法访问的剪贴板时,会提示安全访问中心,是否要跳转到 www.luogu.com/xxx ,检测到这个页面后,脚本会在页面上覆盖一个全屏 iframe 访问模版剪贴板,之所以用 iframe 是为了尽可能实现原生体验,实现 1:1 还原洛谷界面,并且能够实现地址栏不动,然后通过动态检测替换掉模版内容,并创建一个更新按钮。## 专栏大部分原理同剪贴板,但是需要做的事更多了,因为右侧的目录并不会自动生成,所以脚本会先遍历文章,然后在右侧创建目录,但是会从模版的目录里提取出相关 CSS 然后使用。并且还会将操作栏的点赞、收藏、不推荐修改为不可点击,并替换文本为保存站的点赞数。然后删除评论区。# 使用受限于原理限制,需要手动创建一个可以正常访问的剪贴板和文章,剪贴板没有特殊要求,但文章需要有三级标题,比如```markdown# 1## 2### 3```然后在浏览器中安装 [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.3// @description 洛谷国内站:用户主页添加个人介绍卡片;陌生剪切板/文章通过 iframe + API 替换内容,支持 CP OAuth 自动登录和工作流更新;修复多实例刷新问题;替换文章分类、点赞收藏数(纯数字)并禁止交互;支持多操作栏;动态替换右侧目录(保留原生样式);修复加载卡死和跨域自动刷新;iframe 内非锚点链接在顶层跳转;修复 heading-anchor 锚点;安全页超时放弃接管,不再刷新;修改页面标题格式;头像链接放行保留抽屉菜单;修复时间显示偏差(UTC解析);使用全局事件委托彻底解决编辑按钮跳转;主页更新按钮宽度自适应;恢复点赞收藏数及禁用交互功能;检测自己主页不再追加个人介绍卡片;修复浏览器返回后页面不更新的问题;修复 getLoginUid 选择器以适配新版导航栏;修复未保存文章/剪切板时页面卡死在加载中,增加“保存”按钮,修复后退与重试// @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.3', 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: '闲话'}};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 formatTime(isoStr) {if (!isoStr) return '未知';const normalized = isoStr.endsWith('Z') ? isoStr : isoStr + 'Z';const d = new Date(normalized);if (isNaN(d.getTime())) return '未知';const pad = n => String(n).padStart(2, '0');return `${d.getUTCFullYear()}-${pad(d.getUTCMonth()+1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`;}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; text-decoration: underline;`;span.textContent = name;span.addEventListener('click', function(e) {e.preventDefault();window.open(`/user/${userId}`, '_blank');});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);}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) return;elements.contentDiv.innerHTML = '加载中...';GM_xmlhttpRequest({method: 'GET',url: `https://api.luogu.me/user/${uid}`,headers: { 'User-Agent': 'Uptime-Kuma' },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;} 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`,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) {contentDiv.innerHTML = p.data.renderedIntroduction || '<p>暂无个人介绍</p>';} 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}`,headers: { 'User-Agent': 'Uptime-Kuma' },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) {console.error('[LGSinLG] 剪切板跨域异常', 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>';forceExternalLinks(markedDiv);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);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)) {replaceSourceContent(initialPre, 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.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');});}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}`,headers: { 'User-Agent': 'Uptime-Kuma' },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) {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]');}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>';forceExternalLinks(contentDiv);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}`;});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 level = parseInt(heading.tagName.charAt(1));const li = templateLi.cloneNode(false);li.className = `title-${level - 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);removeComments(doc);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);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 });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] 文章接管完成(含点赞收藏及编辑事件委托)');}} 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)) {replaceSourceContent(initialPre, 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.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 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 被调用');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] 检测到跨域错误,即将刷新页面');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', 'User-Agent': 'Uptime-Kuma', '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')) return;if (!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;const iframes = ['lgsinlg-paste-iframe', 'lgsinlg-article-iframe'];iframes.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')) {console.log('[LGSinLG] 进入 OAuth 回调处理');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()) {console.log('[LGSinLG] 当前为安全页,直接进入粘贴接管');handlePastePage(pasteId);return;}console.log('[LGSinLG] 开始轮询等待安全页以接管粘贴');waitForSecurity(pasteId, 'paste');return;}if (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] 检测到自己的主页,跳过个人介绍卡片');removeUserCardIfExists();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=${id})`);if (type === 'paste') handlePastePage(id);else handleArticlePage(id);return;}if (++attempts < maxAttempts) {waitForSecurityTimer = setTimeout(check, 200);} else {console.warn(`[LGSinLG] 安全页等待超时 (${maxAttempts} 次),放弃接管`);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 });// 修复:popstate 中增加错误 UI 检测,直接刷新页面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);}})();```::::最后在脚本的 USER_CONFIG 内设置 templatePasteId 为你刚刚创建的剪贴板的 ID ,templateArticleId 为你刚刚创建的文章 ID ,ID 就是地址栏最后那一串字符,如果模版 ID 无法访问,通常会提示页面结构加载超时。# 注意事项受限于 API 限制以及其他原因,一些功能不方便实现,比如文章评论区显示功能,并且由于是第三方渲染的 Markdown ,一些洛谷 Markdown 特性无法渲染出来。并且脚本依赖于洛谷的前端命名,如果未来更新了,脚本可能会失效。剪切板和文章不能删除,否则会导致功能异常。因为仅对页面表面文字进行了替换,一些依赖于页面信息的脚本如 copy-markdown 将无法正确获取文章的 Markdown 。# 结语欢迎大家使用,如果有 BUG 请在评论区反馈。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778:::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 获取用户、文章、剪贴板信息,嵌入到洛谷当中。# 功能- 非自己、管理员的主页从保存站获取个人简介并追加卡片。- 访问无法访问的剪贴板时自动嵌入内容。- 访问无法访问的文章时自动嵌入内容。- 在文章、个人简介、剪贴板处可以发送保存站更新请求。- 文章、剪切板注入样式实现语法高亮以及 Markdown 框折叠。# 截图个人专栏个人主页剪贴板# 原理## 个人简介通过 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 中查看。