正文
增加 92 行删除 132 行
54 行未改动555657585960616263643 行未改动686970717273747576111 行未改动全部展开188189190191192193194195196197198199200201202203204205206207208209210211147 行未改动全部展开3593603613623633643653663674 行未改动3723733743753763773783793803813823832 行未改动3863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164179 行未改动42742842943043143243343443543643743819 行未改动4584594604614624634644655 行未改动4714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165178 行未改动5265275285295305315325335349 行未改动5445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755766 行未改动58358458558658758858959059159259359418 行未改动6136146156166176186196206216226236246252 行未改动6286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646655 行未改动67167267367467567667767867915 行未改动6956966976986997007017027034 行未改动7087097107117127137147157167177187197209 行未改动7307317327337347357367377387397407412 行未改动7447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937945 行未改动8008018028038048058068078084 行未改动8138148158168178188198208219 行未改动83183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886911 行未改动8818828838848858868878888898905 行未改动8968978988999009019029039049053 行未改动9099109119129139149159169178 行未改动9269279289299309319329339349359368 行未改动9459469479489499509519529539549559569579589599609616 行未改动9689699709719729739749759769779789799809819829839849853 行未改动989990991992993994995996997998999100017 行未改动10181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410 行未改动1055105610571058105910601061106210631064106510661067106810691070107110721073107410753 行未改动10791080108110821083108410851086108716 行未改动1104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911305 行未改动11361137113811391140114111421143114411451146114714 行未改动116211631164116511661167116811691170117111721173117411751176117711781179118011811182118343 行未改动12271228122912301231123212331234123512361237123812 行未改动1251125212531254125512561257125812598 行未改动54 行未改动```javascript// ==UserScript==// @name LGSinLG// @namespace https://www.luogu.com.cn/user/1816684// @version 1.0.1// @description 洛谷国内站:用户主页添加个人介绍卡片;陌生剪切板/文章通过 iframe + API 替换内容,支持 CP OAuth 自动登录和工作流更新;修复多实例刷新问题;替换文章分类、点赞收藏数(纯数字)并禁止交互;支持多操作栏;动态替换右侧目录(保留原生样式);修复加载卡死和跨域自动刷新;iframe 内非锚点链接在顶层跳转;修复 heading-anchor 锚点;安全页超时放弃接管,不再刷新;修改页面标题格式;头像链接放行保留抽屉菜单;修复时间显示偏差(UTC解析);使用全局事件委托彻底解决编辑按钮跳转;主页更新按钮宽度自适应;恢复点赞收藏数及禁用交互功能;检测自己主页不再追加个人介绍卡片;修复浏览器返回后页面不更新的问题// @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.1', new Date().toISOString());window.addEventListener('unhandledrejection', function(event) {console.error('[LGSinLG] 未捕获的 Promise 拒绝:', event.reason);console.error('[LGSinLG] 当前 URL:', location.href);111 行未改动全部展开const card = document.getElementById(CARD_ID);if (card) card.remove();}// 获取当前登录用户ID(从头部导航栏的用户头像链接提取)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/"]'];for (const sel of selectors) {const el = document.querySelector(sel);if (el) {const match = el.getAttribute('href').match(/\/user\/(\d+)/);if (match) return match[1];}}return null;}function getOrCreateCard(uid) {147 行未改动全部展开}});}// ========== iframe 加载辅助函数 ==========function waitForIframeLoad(iframe, timeoutMs = 20000) {return new Promise((resolve, reject) => {const timer = setTimeout(() => {console.warn('[LGSinLG] iframe 加载超时');4 行未改动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);2 行未改动} catch (e) {}});}// ========== 设置 iframe 内全局链接拦截(放行头像链接) ==========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;9 行未改动<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', () => {window.__LGSinLG_paste_handled = false;document.body.innerHTML = '';processRoute();});const iframe = document.createElement('iframe');iframe.id = 'lgsinlg-paste-iframe';19 行未改动onerror() { reject(new Error('网络请求失败')); }});});Promise.all([iframeLoad, apiPromise]).then(([_, pasteData]) => {console.log('[LGSinLG] 剪切板 iframe 和 API 加载完成');const performCoreReplace = () => {5 行未改动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';const authorName = pasteData.author.name;const authorId = pasteData.author.id;authorCaption.innerHTML = '作者: ';authorCaption.appendChild(createClickableUsername(authorName, color, authorId));}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('页面结构加载超时');return;}const doc = iframe.contentDocument || iframe.contentWindow.document;setupLinkInterceptor(doc);8 行未改动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);9 行未改动}});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);handleAutoRefresh(err);});function showError(msg) {document.getElementById('lgsinlg-loading').style.display = 'none';document.getElementById('lgsinlg-error').style.display = 'block';document.getElementById('lgsinlg-error-msg').textContent = '加载失败:' + msg;const ifr = document.getElementById('lgsinlg-paste-iframe');if (ifr) ifr.remove();window.__LGSinLG_paste_handled = false;window.__LGSinLG_active = false;console.warn('[LGSinLG] 剪切板显示错误:', msg);}}// ========== 文章接管(核心:事件委托 + 点赞收藏替换 + 编辑按钮劫持) ==========function handleArticlePage(articleId) {console.log('[LGSinLG] 进入文章接管,articleId:', articleId);if (articleId === USER_CONFIG.templateArticleId) return;if (window.__LGSinLG_article_handled) return;6 行未改动<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', () => {window.__LGSinLG_article_handled = false;document.body.innerHTML = '';processRoute();});const iframe = document.createElement('iframe');iframe.id = 'lgsinlg-article-iframe';18 行未改动onerror() { reject(new Error('网络请求失败')); }});});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;2 行未改动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) {5 行未改动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 {15 行未改动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');4 行未改动}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 = '作者:';9 行未改动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 => {2 行未改动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('页面结构加载超时');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')) {5 行未改动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;4 行未改动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);9 行未改动}});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);handleAutoRefresh(err);});function showError(msg) {document.getElementById('lgsinlg-loading').style.display = 'none';document.getElementById('lgsinlg-error').style.display = 'block';document.getElementById('lgsinlg-error-msg').textContent = '加载失败:' + msg;const ifr = document.getElementById('lgsinlg-article-iframe');if (ifr) ifr.remove();window.__LGSinLG_article_handled = false;window.__LGSinLG_active = false;console.warn('[LGSinLG] 文章显示错误:', msg);}}// ========== 操作栏统一处理函数:点赞收藏数替换 + 编辑按钮劫持 ==========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 => {11 行未改动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;5 行未改动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');3 行未改动}btn.setAttribute(MARKER_DISLIKE, 'true');}});const editLinks = actionsDiv.querySelectorAll('a[href*="/edit"]');editLinks.forEach(link => {if (link.hasAttribute(MARKER_EDIT)) return;link.removeAttribute('href');8 行未改动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();8 行未改动}function getStoredToken() { return GM_getValue('lgs_token', ''); }function triggerWorkflowWithLogin(btn, targetId, type) {if (btn.disabled || btn.style.pointerEvents === 'none') return;const storedToken = getStoredToken();if (storedToken) {executeWorkflow(btn, targetId, type, storedToken);return;}setButtonState(btn, '登录中...');const authWindow = window.open('https://api.luogu.me/auth/cp/login', 'lgs-login', 'width=600,height=700');if (!authWindow) {alert('请允许弹出窗口以完成登录');6 行未改动const token = getStoredToken();if (token) {clearInterval(pollTimer);authWindow.close();executeWorkflow(btn, targetId, type, token);} else if (authWindow.closed || ++pollCount > maxPoll) {clearInterval(pollTimer);resetButtonState(btn, '更新');}}, 500);}function executeWorkflow(btn, targetId, type, token) {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}`,3 行未改动try {const data = JSON.parse(res.responseText);if (data.code === 200) {resetButtonState(btn, '更新');} else {if (data.code === 401) {GM_setValue('lgs_token', '');alert('登录已过期,请再次点击“更新”按钮重新登录');} else {alert('工作流启动失败:' + (data.message || '未知错误'));}resetButtonState(btn, '更新');17 行未改动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() {10 行未改动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;// 移除可能残留的 iframe 和加载 UI(reload 会重建,但提前清理更干净)const iframes = ['lgsinlg-paste-iframe', 'lgsinlg-article-iframe'];iframes.forEach(id => {const el = document.getElementById(id);if (el) el.remove();3 行未改动const error = document.getElementById('lgsinlg-error');if (error) error.remove();}// ========== 主路由调度 ==========let currentPath = location.pathname;let pending = false;let waitForSecurityTimer = null;16 行未改动function processRoute() {recoverActiveIfNeeded();console.log('[LGSinLG] processRoute 开始,active:', window.__LGSinLG_active, 'path:', location.pathname);// ========== 修改点:接管失效检测 ==========if (window.__LGSinLG_active) {const currentPasteId = getPasteIdFromUrl();const currentArticleId = getArticleIdFromUrl();// 如果 URL 仍是之前接管的剪切板或文章页面,则忽略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();5 行未改动if (waitForSecurityTimer) {clearTimeout(waitForSecurityTimer);waitForSecurityTimer = null;}const pasteId = getPasteIdFromUrl();const articleId = getArticleIdFromUrl();if (pasteId) {console.log('[LGSinLG] 检测到粘贴页 pasteId:', pasteId);if (isSecurityPage()) {console.log('[LGSinLG] 当前为安全页,直接进入粘贴接管');14 行未改动console.log('[LGSinLG] 开始轮询等待安全页以接管文章');waitForSecurity(articleId, 'article');return;}const uid = getUserIdFromUrl();if (uid) {console.log('[LGSinLG] 检测到用户页 uid:', uid);const loginUid = getLoginUid();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();43 行未改动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);currentPath = location.pathname;// popstate 时 processRoute 会进行接管失效检测,无需额外处理processRoute();});if (getPasteIdFromUrl() || getArticleIdFromUrl() || (location.hostname.endsWith('.luogu.me') && location.pathname.startsWith('/auth/callback'))) {12 行未改动})();```::::最后在脚本的 USER_CONFIG 内设置 templatePasteId 为你刚刚创建的剪贴板的 ID ,templateArticleId 为你刚刚创建的文章 ID 。# 注意事项受限于 API 限制以及其他原因,一些功能不方便实现,比如文章评论区显示功能,并且由于是第三方渲染的 Markdown ,一些洛谷 Markdown 特性无法渲染出来。并且脚本依赖于洛谷的前端命名,如果未来更新了,脚本可能会失效。8 行未改动54 行未改动555657585960616263643 行未改动686970717273747576111 行未改动全部展开188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218147 行未改动全部展开3663673683693703713723734 行未改动3783793803813823833843853863872 行未改动3903913923933943953963973983994004014024034044054064074084094104114124134144154164179 行未改动42742842943043143243343443543643719 行未改动4574584594604614624634644654664674684694704714724734744754764774784794804814824834844854865 行未改动4924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295308 行未改动5395405415425435445455469 行未改动5565575585595605615625635645655665675685695705715725735745756 行未改动58258358458558658758858959059159218 行未改动6116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436442 行未改动6476486496506516526536546556566576586596606616626636646656666676686696706716726736746756765 行未改动68268368468568668768868915 行未改动7057067077087097107117124 行未改动7177187197207217227237247257267279 行未改动7377387397407417427437447452 行未改动7487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897905 行未改动7967977987998008018028034 行未改动8088098108118128138148159 行未改动82582682782882983083183283383483583683783883984084184284384484584684784884911 行未改动8618628638648658668678688695 行未改动8758768778788798808818828833 行未改动8878888898908918928938948 行未改动9039049059069079089099109118 行未改动9209219229239249259269279289299309319329339346 行未改动9419429439449459469479489499509519529539549559569579583 行未改动96296396496596696796896997097197297397417 行未改动992993994995996997998999100010011002100310041005100610071008100910101011101210 行未改动102310241025102610271028102910301031103210331034103510361037103810393 行未改动1043104410451046104710481049105016 行未改动1067106810691070107110721073107410751076107710781079108010811082108310841085108610875 行未改动109310941095109610971098109911001101110214 行未改动11171118111911201121112211231124112511261127112811291130113111321133113411351136113743 行未改动11811182118311841185118611871188118911901191119211931194119511961197119812 行未改动1211121212131214121512161217121812198 行未改动54 行未改动```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_xmlhttpRequest3 行未改动(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);111 行未改动全部展开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) {147 行未改动全部展开}});}function waitForIframeLoad(iframe, timeoutMs = 20000) {return new Promise((resolve, reject) => {const timer = setTimeout(() => {console.warn('[LGSinLG] iframe 加载超时');4 行未改动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);2 行未改动} 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;9 行未改动<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';19 行未改动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 = () => {5 行未改动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);8 行未改动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);9 行未改动}});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;6 行未改动<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';18 行未改动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;2 行未改动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) {5 行未改动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 {15 行未改动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');4 行未改动}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 = '作者:';9 行未改动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 => {2 行未改动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')) {5 行未改动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;4 行未改动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);9 行未改动}});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 => {11 行未改动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;5 行未改动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');3 行未改动}btn.setAttribute(MARKER_DISLIKE, 'true');}});const editLinks = actionsDiv.querySelectorAll('a[href*="/edit"]');editLinks.forEach(link => {if (link.hasAttribute(MARKER_EDIT)) return;link.removeAttribute('href');8 行未改动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();8 行未改动}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('请允许弹出窗口以完成登录');6 行未改动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}`,3 行未改动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, '更新');17 行未改动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() {10 行未改动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();3 行未改动const error = document.getElementById('lgsinlg-error');if (error) error.remove();}let currentPath = location.pathname;let pending = false;let waitForSecurityTimer = null;16 行未改动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();5 行未改动if (waitForSecurityTimer) {clearTimeout(waitForSecurityTimer);waitForSecurityTimer = null;}const pasteId = getPasteIdFromUrl();const articleId = getArticleIdFromUrl();if (pasteId) {console.log('[LGSinLG] 检测到粘贴页 pasteId:', pasteId);if (isSecurityPage()) {console.log('[LGSinLG] 当前为安全页,直接进入粘贴接管');14 行未改动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();43 行未改动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'))) {12 行未改动})();```::::最后在脚本的 USER_CONFIG 内设置 templatePasteId 为你刚刚创建的剪贴板的 ID ,templateArticleId 为你刚刚创建的文章 ID ,ID 就是地址栏最后那一串字符,如果模版 ID 无法访问,通常会提示页面结构加载超时。# 注意事项受限于 API 限制以及其他原因,一些功能不方便实现,比如文章评论区显示功能,并且由于是第三方渲染的 Markdown ,一些洛谷 Markdown 特性无法渲染出来。并且脚本依赖于洛谷的前端命名,如果未来更新了,脚本可能会失效。8 行未改动