版本比较
在洛谷内无缝访问所有文章
正文
增加 92 行删除 132 行
54 行未改动5556575859605960616263643 行未改动68697071727273747576111 行未改动全部展开188189190191192192193194195196197199198199200201202203204205206207205208209210211212213214215216217218147 行未改动全部展开3663673683693633703713723734 行未改动3783793803813763823833793843853863872 行未改动3903913923933903943953963973983994003984014024034044034054064074084094104114124134134144154164179 行未改动42742842943043143243243343443343443543643719 行未改动4574584594604614624634644654664674684694704714724734744754764774784794804814824834844854865 行未改动4924934944954754964974984994805005014835025035044874885054905065074925085095104965115125135145155165175185195065205215225235245255135265275285295308 行未改动5395405415425305435445455469 行未改动5565575585595485605615625635645655665675575685695595605615625635645655665675685695705715725725735745756 行未改动58258358458558658758858959058858959059159218 行未改动6116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406216416426436442 行未改动6476486496506326516526536546376556566576586596606616456626476636646656516666676686696706576586596716726616736746756765 行未改动68268368468567568668768868915 行未改动7057067077086997097107117124 行未改动7177187197207127217227237167247257267279 行未改动7377387397407347357417377427437447452 行未改动7487497507517487497507517527527537547557567577587597607617627627637647657667677677687697707717727747737747757767777797787797807817827857837847857867907877887897905 行未改动7967977987998048008018028034 行未改动8088098108118178128138148159 行未改动82582682782883582983083183283383483583684483783884684784884985085185285385485585683984085984184284384484586584684784884911 行未改动8618628638648858868658668678688695 行未改动8758768778789009018798808818828833 行未改动8878888898909138918928938948 行未改动9039049059069309319329079089099109118 行未改动9209219229239499249259519269279549289299309579319329339346 行未改动9419429439449729459469479489499509519529809819539549559569579583 行未改动96296396496596696796896999697097197297397417 行未改动9929939949951022102310241025102699699799899910001001100210031004100510061036103710381039104010071008100910101011101210 行未改动1023102410251026105910271028106210291030103110321067103310341035107110361037103810393 行未改动10431044104510461083104710481049105016 行未改动1067106810691070110811091071107210731113107410751076107710781119107910801081108210831125112610841085108610875 行未改动10931094109510961140109710981143109911001101110214 行未改动1117111811191120116611211122112311241125112611271128112911301131113211331179113411351136113743 行未改动118111821183118411851186118711881189119011911192119311941234119511961197119812 行未改动12111212121312141255121512161217121812198 行未改动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解析);使用全局事件委托彻底解决编辑按钮跳转;主页更新按钮宽度自适应;恢复点赞收藏数及禁用交互功能;检测自己主页不再追加个人介绍卡片;修复浏览器返回后页面不更新的问题// @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.1', new Date().toISOString()); 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(); }
// 获取当前登录用户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/"]' '.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) return match[1]; if (match) { console.log('[LGSinLG] getLoginUid 匹配到:', sel, 'ID:', match[1]); return match[1]; } } } console.warn('[LGSinLG] getLoginUid 未找到登录用户ID'); 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(); 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'; const authorName = pasteData.author.name; const authorId = pasteData.author.id; authorCaption.innerHTML = '作者: '; authorCaption.appendChild(createClickableUsername(authorName, color, authorId)); 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('页面结构加载超时'); 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); handleAutoRefresh(err); showError('该剪切板尚未被保存站收录', pasteId, 'paste'); });
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(); 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}`; } 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; } 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('页面结构加载超时'); 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); handleAutoRefresh(err); showError('该文章尚未被保存站收录', articleId, 'article'); });
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)) { } 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)) { } 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); } 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) { function triggerWorkflowWithLogin(btn, targetId, type, onSuccess) { if (btn.disabled || btn.style.pointerEvents === 'none') return;
const storedToken = getStoredToken(); if (storedToken) { executeWorkflow(btn, targetId, type, 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); executeWorkflow(btn, targetId, type, token, onSuccess); } else if (authWindow.closed || ++pollCount > maxPoll) { clearInterval(pollTimer); resetButtonState(btn, '更新'); } }, 500); }
function executeWorkflow(btn, targetId, type, token) { setButtonState(btn, '已发送'); 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('登录已过期,请再次点击“更新”按钮重新登录'); 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'; } 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 = ''; } 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(); 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; // popstate 时 processRoute 会进行接管失效检测,无需额外处理 processRoute(); });
if (getPasteIdFromUrl() || getArticleIdFromUrl() || (location.hostname.endsWith('.luogu.me') && location.pathname.startsWith('/auth/callback'))) {12 行未改动})();```::::
最后在脚本的 USER_CONFIG 内设置 templatePasteId 为你刚刚创建的剪贴板的 ID ,templateArticleId 为你刚刚创建的文章 ID 。最后在脚本的 USER_CONFIG 内设置 templatePasteId 为你刚刚创建的剪贴板的 ID ,templateArticleId 为你刚刚创建的文章 ID ,ID 就是地址栏最后那一串字符,如果模版 ID 无法访问,通常会提示页面结构加载超时。
# 注意事项
受限于 API 限制以及其他原因,一些功能不方便实现,比如文章评论区显示功能,并且由于是第三方渲染的 Markdown ,一些洛谷 Markdown 特性无法渲染出来。并且脚本依赖于洛谷的前端命名,如果未来更新了,脚本可能会失效。8 行未改动