版本比较
在洛谷内无缝访问所有文章
正文
增加 660 行删除 455 行
11 行未改动1213141516161718192021212223242530 行未改动5657585960616061626364653 行未改动69707172737374757677787980818283848586868788899016 行未改动10710810911011111211311411511611111211311411511611711811912012112212312412512612712811811912012112212913013113213313413513613713813914014114212412514314414514614712712814813013113213313413513613713813914014114214314414915015115215315415515615715815916016116216316416516614614716716814915015115215315415515615716917017117217317417517617717817918018118218318418518618718818919019119219319419515916016116216316416519619719819920020120220320420520620720820921016716816917017117217321121221317517617717821421521621718021821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431515 行未改动33133233333420433533633733833934034134234321234434534621434734834935035135219 行未改动372373374375376377378244379380381382248249250251252253254255256257258383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412260261262263264265266267268413414415416417418419420272421422423274275276277278279280281282283284285286287288424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461291462463464465191 行未改动全部展开65765865966049149266166266366466566666766866967067167267367467567667767867968068168268368449449549649749849950050150250350450550650750850951051151251351451551651751868568668768868969069169269369469552069669769869970070170270370452352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455570570670770870971071171271371471571671771871972072172272372455772555956056156256356456556656756872672772872973073173273373457057157257357457573573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077157757857958077258258358458558658758858959059159259359459559659759859960060160260360477377477577677777877978078178278378460660760860961061161261361461561661761878578678778878979079179279379479579679779879962062162262362462562662762880080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583663083783883984084184284384484584684784884985085185285385485585685785885986086186286386463363463563663763863964064186586664464564664764864965065165265365465565665765865966066166266366466566666766886786886987015 行未改动88688788888969289089189289335 行未改动9299309319327369339347389359369379382 行未改动94194294394474975075175294594694794875794995095195295395495595676695776895895996077296196296396496596696796878096997097197228 行未改动100110021003100481710051006100710084 行未改动1013101410151016830101710181019102012 行未改动10331034103510368511037103810391040104114 行未改动105610571058105987410601061106287810631064106510663 行未改动1070107110721073107410751076107710781079108018 行未改动10991100110111029161103110411051106110711081109111092411111112111311149 行未改动112411251126112794211281129113011314 行未改动113611371138113995595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599611401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001000100110021003100410051006100710081009101010111012101310141015101612011202120312041205120612071208120912101211121212131214101812151216121712181219122010221023102410251026102710281029103010311032103310341221122210361223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125110381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831252125312541255125612571258125912601261126212631264126512661267126812691270127112721085108610871088127312741090109110921093109410951096109710981099110011011102110311041105110611071275127612771278127912801281128212831284128512861287111011111112111311141115111611171118111912881289129012911292129312941295129612971298112212991300130113021303130413051306130713081309131013111312131313147 行未改动1322132313241325113811391140114111421326132713281329133013311332133313341152133513361337133813391340134113421343134413451346134713481349135013511352135317 行未改动13711372137313741375137613771378137913801381138213831384138513861387138813891390139113922 行未改动139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143412321233123412351435143614371438143914401441144220 行未改动14631464146514661264146714681469147011 行未改动148214831484148512841486148714881489149014911492149314941495129214961497149814991500150115021503150415051506150718 行未改动11 行未改动- 非自己、管理员的主页从保存站获取个人简介并追加卡片。- 访问无法访问的剪贴板时自动嵌入内容。- 访问无法访问的文章时自动嵌入内容。- 在文章、个人简介、剪贴板处可以发送保存站更新请求。- 从 Github 自动获取保存站样式实现语法高亮。- 文章、剪切板注入样式实现语法高亮以及 Markdown 框折叠。
# 截图
个人专栏
个人主页
30 行未改动```javascript// ==UserScript==// @name LGSinLG// @namespace https://www.luogu.com.cn/user/1816684// @version 1.0.6// @description 洛谷国内站:用户主页添加个人介绍卡片;陌生剪切板/文章通过 iframe + API 替换内容,支持 CP OAuth 自动登录和工作流更新;修复多实例刷新问题;替换文章分类、点赞收藏数(纯数字)并禁止交互;支持多操作栏;动态替换右侧目录(保留原生样式);修复加载卡死和跨域自动刷新;iframe 内非锚点链接在顶层跳转;修复 heading-anchor 锚点;安全页超时放弃接管,不再刷新;修改页面标题格式;头像链接放行保留抽屉菜单;修复时间显示为本地时间;使用全局事件委托彻底解决编辑按钮跳转;主页更新按钮宽度自适应;恢复点赞收藏数及禁用交互功能;检测自己主页不再追加个人介绍卡片;修复浏览器返回后页面不更新的问题;修复 getLoginUid 选择器以适配新版导航栏;修复未保存文章/剪切板时页面卡死在加载中,增加“保存”按钮,修复后退与重试;修复图片宽度溢出问题;注入官方 Markdown/代码高亮样式,完美还原保存站外观// @version 1.0.7// @description 洛谷国内站:用户主页添加个人介绍卡片;陌生剪切板/文章通过 iframe + API 替换内容,支持 CP OAuth 自动登录和工作流更新;修复多实例刷新问题;替换文章分类、点赞收藏数(纯数字)并禁止交互;支持多操作栏;动态替换右侧目录(保留原生样式);修复加载卡死和跨域自动刷新;iframe 内非锚点链接在顶层跳转;修复 heading-anchor 锚点;安全页超时放弃接管,不再刷新;修改页面标题格式;头像链接放行保留抽屉菜单;修复时间显示为本地时间;使用全局事件委托彻底解决编辑按钮跳转;主页更新按钮宽度自适应;恢复点赞收藏数及禁用交互功能;检测自己主页不再追加个人介绍卡片;修复浏览器返回后页面不更新的问题;修复 getLoginUid 选择器以适配新版导航栏;修复未保存文章/剪切板时页面卡死在加载中,增加“保存”按钮,修复后退与重试;修复图片宽度溢出问题;注入 Shiki 代码块专用样式,完美显示代码高亮、行号,不影响侧边栏及其他区域;添加 md-block 折叠展开(按钮位于标题最右侧);代码块复制按钮;修复 md-block 标题图标与文字重叠// @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.6', new Date().toISOString()); console.log('[LGSinLG] 脚本启动,版本 1.0.7', 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: {16 行未改动 8: '闲话' } };
// 样式 URL(直接从 GitHub 拉取,无需指定哈希) const STYLE_URLS = { global: 'https://raw.githubusercontent.com/Ark-Aak/luogu-saver-next/master/packages/frontend/src/styles/global.css', markdown: 'https://raw.githubusercontent.com/Ark-Aak/luogu-saver-next/master/packages/frontend/src/styles/markdown.css', katex: 'https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css' }; // Shiki 代码块专用样式(不影响页面其它区域) const SHIKI_CSS = ` /* 激活 Shiki 内联颜色变量 */ .shiki, .shiki span { color: var(--shiki-light, #24292e); } .shiki { background-color: var(--shiki-light-bg, #f6f8fa); } @media (prefers-color-scheme: dark) { .shiki, .shiki span { color: var(--shiki-dark, #c9d1d9); } .shiki { background-color: var(--shiki-dark-bg, #0d1117); } }
// 最小备用样式(保证代码块基本可读) const FALLBACK_CSS = ` .marked { word-break: break-word; line-height: 1.7; } .shiki, .shiki span { color: var(--shiki-light, #24292e); } .shiki { background-color: var(--shiki-light-bg, #f6f8fa); padding: 16px; border-radius: 6px; border: 1px solid #d0d7de; overflow-x: auto; font-family: monospace; font-size: 13px; line-height: 1.5; margin: 1em 0; } /* 代码块容器外观 */ pre.shiki { padding: 16px; border-radius: 8px; border: 1px solid #d0d7de; background-color: #f6f8fa !important; overflow-x: auto; font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 13px; line-height: 1.5; tab-size: 4; margin: 1em 0; } @media (prefers-color-scheme: dark) { .shiki, .shiki span { color: var(--shiki-dark, #c9d1d9); } .shiki { background-color: var(--shiki-dark-bg, #0d1117); border-color: #30363d; } pre.shiki { background-color: #0d1117 !important; border-color: #30363d; } } .katex { font-size: 1.1em; } `;
// ==================== 样式预加载与缓存 ==================== function updateStyleCache(url, key) { GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(res) { if (res.status === 200) { GM_setValue(key, res.responseText); console.log('[LGSinLG] 样式已更新:', key); } else { console.warn('[LGSinLG] 样式拉取失败,状态码:', res.status, url); } }, onerror: function(err) { console.error('[LGSinLG] 样式拉取网络错误:', err); /* 行号(纯 CSS 实现) */ .shiki { counter-reset: line; } .shiki .line::before { counter-increment: line; content: counter(line); display: inline-block; width: 2em; margin-right: 1em; text-align: right; color: #8c959f; user-select: none; } @media (prefers-color-scheme: dark) { .shiki .line::before { color: #484f58; } }); } }
// 每天自动更新一次样式缓存 const now = Date.now(); const lastStyleUpdate = GM_getValue('lgs_style_update_time', 0); if (now - lastStyleUpdate > 86400000) { updateStyleCache(STYLE_URLS.global, 'lgs_css_global'); updateStyleCache(STYLE_URLS.markdown, 'lgs_css_markdown'); updateStyleCache(STYLE_URLS.katex, 'lgs_css_katex'); GM_setValue('lgs_style_update_time', now); } /* 行内高亮 */ .code-line.highlight { background: rgba(255, 229, 100, 0.25); } /* 自定义容器(md-block) */ .md-block.info, .md-block.warning, .md-block.success, .md-block.error { border: 0 solid rgba(228, 228, 228, 0); border-left-width: 6px; padding: 10px; margin: 12px 0; } .md-block.info { border-left-color: #7da7ff; } .md-block.warning { border-left-color: #ffb454; } .md-block.success { border-left-color: #4dd27a; } .md-block.error { border-left-color: #ff5757; }
// 首次运行时立即拉取(如果没有缓存) if (!GM_getValue('lgs_css_global')) { updateStyleCache(STYLE_URLS.global, 'lgs_css_global'); updateStyleCache(STYLE_URLS.markdown, 'lgs_css_markdown'); updateStyleCache(STYLE_URLS.katex, 'lgs_css_katex'); GM_setValue('lgs_style_update_time', now); } .md-block > .md-block-title { font-weight: 700; display: flex; justify-content: space-between; align-items: center; color: inherit; margin-bottom: 4px; position: relative; padding-left: 1.8em; /* 为左侧图标预留空间,防止重叠 */ } .md-block.info > .md-block-title { color: #7da7ff; } .md-block.warning > .md-block-title { color: #ffb454; } .md-block.success > .md-block-title { color: #4dd27a; } .md-block.error > .md-block-title { color: #ff5757; }
// 获取最终注入样式(有缓存用缓存,无缓存用备用) function getCombinedCSS() { const globalCSS = GM_getValue('lgs_css_global', ''); const markdownCSS = GM_getValue('lgs_css_markdown', ''); const katexCSS = GM_getValue('lgs_css_katex', ''); if (globalCSS && markdownCSS && katexCSS) { return katexCSS + '\n' + globalCSS + '\n' + markdownCSS; .md-block > .md-block-body { margin-top: 4px; } // 若部分缺失,使用备用样式 console.warn('[LGSinLG] 样式缓存不完整,使用备用样式'); return FALLBACK_CSS; } .md-block > .md-block-body > p:last-child { margin-bottom: 0; }
// ==================== 工具函数 ==================== /* 标题前的图标(绝对定位,不占用 flex 空间) */ .md-block > .md-block-title::before { content: ''; display: inline-block; width: 1em; height: 1em; background-color: currentColor; -webkit-mask-repeat: no-repeat; mask-repeat: no-repeat; -webkit-mask-size: contain; mask-size: contain; position: absolute; left: 0.2em; /* 微调位置,与左边框对齐 */ top: 50%; transform: translateY(-50%); }
/* 成功(绿色勾) */ .md-block.success > .md-block-title::before { -webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM369 209L241 337c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L335 175c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/></svg>'); mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM369 209L241 337c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L335 175c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/></svg>'); }
/* 警告(黄色感叹号) */ .md-block.warning > .md-block-title::before { -webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zm0-384c13.3 0 24 10.7 24 24V264c0 13.3-10.7 24-24 24s-24-10.7-24-24V152c0-13.3 10.7-24 24-24zM224 352a32 32 0 1 1 64 0 32 32 0 1 1 -64 0z"/></svg>'); mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zm0-384c13.3 0 24 10.7 24 24V264c0 13.3-10.7 24-24 24s-24-10.7-24-24V152c0-13.3 10.7-24 24-24zM224 352a32 32 0 1 1 64 0 32 32 0 1 1 -64 0z"/></svg>'); }
/* 信息(蓝色 i 图标) */ .md-block.info > .md-block-title::before { -webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"/></svg>'); mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"/></svg>'); }
/* 错误(红色叉) */ .md-block.error > .md-block-title::before { -webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM175 175c9.4-9.4 24.6-9.4 33.9 0l47 47 47-47c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-47 47 47 47c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0l-47-47-47 47c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l47-47-47-47c-9.4-9.4-9.4-24.6 0-33.9z"/></svg>'); mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"%20viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM175 175c9.4-9.4 24.6-9.4 33.9 0l47 47 47-47c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-47 47 47 47c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0l-47-47-47 47c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l47-47-47-47c-9.4-9.4-9.4-24.6 0-33.9z"/></svg>'); }
/* 钉子锚点 */ .heading-pin-icon { width: 18px; height: 18px; stroke-width: 2; }
/* === 折叠按钮样式 === */ .md-block-title { cursor: pointer; user-select: none; } .toggle-icon { display: inline-block; transition: transform 0.25s; margin-left: 0.5em; font-size: 0.9em; line-height: 1; flex-shrink: 0; } .toggle-icon.collapsed { transform: rotate(-90deg); }
/* === 代码块复制按钮样式 === */ .shiki-wrapper { position: relative; } .shiki-copy-btn { position: absolute; top: 8px; right: 8px; background: rgba(0,0,0,0.05); border: 1px solid #d0d7de; border-radius: 4px; padding: 2px 8px; font-size: 12px; cursor: pointer; opacity: 0; transition: opacity 0.2s; z-index: 5; } .shiki-wrapper:hover .shiki-copy-btn { opacity: 1; } @media (prefers-color-scheme: dark) { .shiki-copy-btn { background: rgba(255,255,255,0.05); border-color: #30363d; } } `;
function getUserIdFromUrl() { const m = location.pathname.match(/^\/user\/(\d+)\/?$/); return m ? m[1] : null; }15 行未改动 }
function constrainImages(container) { if (!container) return; container.querySelectorAll('img').forEach(img => { const imgs = container.querySelectorAll('img'); imgs.forEach(img => { img.style.maxWidth = '100%'; img.style.height = 'auto'; }); }
function forceExternalLinks(container) { if (!container) return; container.querySelectorAll('a').forEach(a => { const links = container.querySelectorAll('a'); links.forEach(a => { let href = a.getAttribute('href'); if (!href || href.startsWith('#')) return; if (!href) return; if (href.startsWith('#')) return; if (href.startsWith('/')) { href = `https://www.luogu.com.cn${href}`; a.setAttribute('href', href); }19 行未改动 if (el) el.remove(); }; remove(); let attempts = 0; const maxAttempts = 10; const timer = setInterval(() => { if (doc.querySelector(commentSelector)) remove(); if (++attempts >= 10) clearInterval(timer); if (++attempts >= maxAttempts) clearInterval(timer); }, 300); }
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 加载失败')); // 注入 Shiki 专用样式到 iframe 的 <head> function injectShikiCSS(doc) { if (!doc || !doc.head) return; const style = doc.createElement('style'); style.textContent = SHIKI_CSS; doc.head.appendChild(style); console.log('[LGSinLG] Shiki 代码块样式已注入'); }
// === 新增:md-block 折叠/展开功能(按钮位于标题最右侧) === function addMdBlockToggle(doc) { if (!doc || !doc.body) return; const blocks = doc.querySelectorAll('.md-block'); blocks.forEach(block => { const title = block.querySelector('.md-block-title'); if (!title) return; if (title.dataset.toggleBound) return;
const body = block.querySelector('.md-block-body'); if (!body) return;
const icon = doc.createElement('span'); icon.className = 'toggle-icon'; icon.textContent = '▸'; title.appendChild(icon);
const toggle = () => { const collapsed = icon.classList.toggle('collapsed'); body.style.display = collapsed ? 'none' : ''; }; 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) {}
title.addEventListener('click', toggle); title.style.cursor = 'pointer'; title.dataset.toggleBound = 'true'; }); console.log('[LGSinLG] md-block 折叠功能已激活'); }
function setupLinkInterceptor(doc) { // === 新增:代码块复制按钮 === function addShikiCopyButtons(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(); window.top.location.href = href; }; doc.body.removeEventListener('click', handler, true); doc.body.addEventListener('click', handler, true); const shikiBlocks = doc.querySelectorAll('pre.shiki'); shikiBlocks.forEach(pre => { if (pre.parentElement && pre.parentElement.classList.contains('shiki-wrapper')) return;
const wrapper = doc.createElement('div'); wrapper.className = 'shiki-wrapper'; pre.parentNode.insertBefore(wrapper, pre); wrapper.appendChild(pre);
const btn = doc.createElement('button'); btn.className = 'shiki-copy-btn'; btn.textContent = '复制'; btn.addEventListener('click', () => { const code = pre.textContent || ''; const copy = (text) => { navigator.clipboard.writeText(text).then(() => { btn.textContent = '已复制'; setTimeout(() => { btn.textContent = '复制'; }, 2000); }).catch(() => { const ta = doc.createElement('textarea'); ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0'; doc.body.appendChild(ta); ta.select(); doc.execCommand('copy'); doc.body.removeChild(ta); btn.textContent = '已复制'; setTimeout(() => { btn.textContent = '复制'; }, 2000); }); }; copy(code); }); wrapper.appendChild(btn); }); console.log('[LGSinLG] 代码块复制按钮已添加'); }
// ==================== 个人介绍卡片 ==================== const CARD_ID = 'lgsinlg-intro-card';
function isAdminUser() { const rows = document.querySelectorAll('.l-flex-info-row');191 行未改动全部展开 } }); }
// ==================== 工作流相关 ==================== function getStoredToken() { return GM_getValue('lgs_token', ''); } 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 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, '更新'); 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; } }, 500); 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 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 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(); }); }
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'; } 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 = '云剪贴板 - 洛谷|计算机教育新生态';
function resetButtonState(btn, text) { const textSpan = btn.querySelector && btn.querySelector('.text'); if (textSpan) { textSpan.textContent = ` ${text} `; } else { btn.textContent = text; 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; } if (btn.tagName === 'BUTTON') btn.disabled = false; else btn.style.pointerEvents = ''; btn.removeAttribute('data-lgs-disabled'); }
// ==================== 文章/剪切板接管核心 ==================== 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'; 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; } 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'; if (!doc) return false; const markedDiv = doc.querySelector('.marked'); const timeCaption = doc.querySelector('.content-card-top .author .lfe-caption:not(.author-margin)'); const actionsDiv = doc.querySelector('.actions'); if (!markedDiv || !timeCaption || !actionsDiv) return false; markedDiv.innerHTML = pasteData.renderedContent || '<p>暂无内容</p>'; constrainImages(markedDiv); forceExternalLinks(markedDiv); injectShikiCSS(doc); const authorCaption = doc.querySelector('.author .lfe-caption.author-margin'); if (authorCaption) { const color = USER_CONFIG.colorMap[pasteData.author.color] || '#000'; authorCaption.innerHTML = '作者: '; authorCaption.appendChild(createClickableUsername(pasteData.author.name, color, pasteData.author.id)); } 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'; const createdTime = formatTime(pasteData.createdAt); const updatedTime = formatTime(pasteData.updatedAt); timeCaption.innerHTML = `发表时间: <time>${createdTime}</time> | 更新: <time>${updatedTime}</time>`; const buttons = actionsDiv.querySelectorAll('button'); buttons.forEach(btn => { btn.style.display = 'none'; }); const updateBtn = document.createElement('button'); updateBtn.type = 'button'; updateBtn.textContent = '更新'; updateBtn.style.cssText = 'background: rgb(52, 152, 219); border: 1px solid rgb(52, 152, 219); border-radius: 3px; color: #fff; cursor: pointer; font-size: 14px; padding: 4px 12px;'; updateBtn.addEventListener('click', () => triggerWorkflowWithLogin(updateBtn, pasteId, 'paste')); actionsDiv.appendChild(updateBtn); return true; }; let attempts = 0; const interval = setInterval(() => { try { if (performCoreReplace() || ++attempts >= 50) { clearInterval(interval); if (!performCoreReplace()) { showError('页面结构加载超时', pasteId, 'paste'); return; } const doc = iframe.contentDocument || iframe.contentWindow.document; setupLinkInterceptor(doc); setupSourceObserver(doc, pasteData.content); // 注入新功能 addMdBlockToggle(doc); addShikiCopyButtons(doc); document.getElementById('lgsinlg-loading').style.display = 'none'; iframe.style.display = ''; window.__LGSinLG_active = true; console.log('[LGSinLG] 剪切板接管完成'); } } catch (e) { clearInterval(interval); console.error('[LGSinLG] 剪切板轮询异常', e); handleAutoRefresh(e); } btn.setAttribute(MARKER_DISLIKE, 'true'); }, 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'); }); const editLinks = actionsDiv.querySelectorAll('a[href*="/edit"]'); editLinks.forEach(link => { if (link.hasAttribute(MARKER_EDIT)) return; link.removeAttribute('href'); const textSpan = link.querySelector('.text'); if (textSpan) textSpan.textContent = ' 更新 '; link.setAttribute(MARKER_EDIT, 'true'); }); }); }
function handleAutoRefresh(error) { console.error('[LGSinLG] handleAutoRefresh 被调用', error); if (error && error.message && (error.message.includes('cross-origin') || error.message.includes('Blocked a frame'))) { console.warn('[LGSinLG] 检测到跨域错误,即将刷新页面'); location.reload(); } else { 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 injectStylesIntoIframe(doc) { if (!doc || !doc.head) return; const combinedCSS = getCombinedCSS(); const style = doc.createElement('style'); style.textContent = combinedCSS; doc.head.appendChild(style); console.log('[LGSinLG] 样式已注入 iframe'); }
// ==================== 文章接管 ==================== function handleArticlePage(articleId) { console.log('[LGSinLG] 进入文章接管,articleId:', articleId); if (articleId === USER_CONFIG.templateArticleId) return; if (window.__LGSinLG_article_handled) return;15 行未改动 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) => {35 行未改动 }
Promise.all([iframeLoad, apiPromise]) .then(([_, articleData]) => { console.log('[LGSinLG] 文章 iframe 和 API 加载完成'); 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;
// 注入样式(在内容替换前执行,确保无闪烁) injectStylesIntoIframe(doc);
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>'; constrainImages(contentDiv); forceExternalLinks(contentDiv);
injectShikiCSS(doc); const headings = contentDiv.querySelectorAll('h1, h2, h3, h4, h5, h6'); headings.forEach((heading, index) => { const newId = `lgs-toc-${index}`; heading.id = newId; const anchorLink = heading.querySelector('a.heading-anchor'); if (anchorLink) anchorLink.href = `#${newId}`; });
const tocContainer = doc.querySelector('.toc'); if (tocContainer) { const tocUl = tocContainer.querySelector('ul'); if (tocUl) {28 行未改动 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) {12 行未改动 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 => {14 行未改动 link.href = `/article?category=${categoryId}`; }); } replaceCategory(doc, articleData.category); hijackActionButtons(doc, articleData, articleId); removeComments(doc); return true; };
let attempts = 0; const interval = setInterval(() => { try { if (performCoreReplace() || ++attempts >= 50) {3 行未改动 return; } const doc = iframe.contentDocument || iframe.contentWindow.document; setupLinkInterceptor(doc); // 注入新功能 addMdBlockToggle(doc); addShikiCopyButtons(doc); const commentObserver = new MutationObserver(() => { const comment = doc.querySelector('.article-comment'); if (comment) comment.remove(); });18 行未改动 setupSourceObserver(doc, articleData.content); document.getElementById('lgsinlg-loading').style.display = 'none'; iframe.style.display = ''; window.__LGSinLG_active = true; console.log('[LGSinLG] 文章接管完成(含完整样式注入)'); 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);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;4 行未改动 showError('该文章尚未被保存站收录', articleId, 'article'); }); }
// ==================== 剪切板接管(同样注入样式) ==================== 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;
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 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 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'); 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(); window.__LGSinLG_paste_handled = false; 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; } }
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; function getStoredToken() { return GM_getValue('lgs_token', ''); }
injectStylesIntoIframe(doc); 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); }
const markedDiv = doc.querySelector('.marked'); const timeCaption = doc.querySelector('.content-card-top .author .lfe-caption:not(.author-margin)'); const actionsDiv = doc.querySelector('.actions'); if (!markedDiv || !timeCaption || !actionsDiv) return false;
markedDiv.innerHTML = pasteData.renderedContent || '<p>暂无内容</p>'; constrainImages(markedDiv); forceExternalLinks(markedDiv);
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] 剪切板接管完成(含样式注入)'); 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 || '未知错误')); } } catch (e) { clearInterval(interval); console.error('[LGSinLG] 剪切板轮询异常', e); handleAutoRefresh(e); resetButtonState(btn, '更新'); } }, 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 }); } catch (e) { alert('响应解析失败'); resetButtonState(btn, '更新'); } }, onerror: function(err) { console.error('[LGSinLG] 网络错误', err); alert('网络错误,请稍后重试'); resetButtonState(btn, '更新'); } }); }
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 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'; }
// ==================== OAuth 回调处理 ==================== 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>';7 行未改动 document.body.innerHTML = '<div style="text-align:center; padding:50px;">登录失败,未获取到 Token,请关闭此窗口后重试。</div>'; } }
// ==================== 路由处理 ==================== let currentPath = location.pathname; let pending = false; let waitForSecurityTimer = null;
function cleanupTakeover() { console.log('[LGSinLG] 执行接管清理'); if (waitForSecurityTimer) { clearTimeout(waitForSecurityTimer); waitForSecurityTimer = null; } window.__LGSinLG_active = false; window.__LGSinLG_paste_handled = false; window.__LGSinLG_article_handled = false; ['lgsinlg-paste-iframe', 'lgsinlg-article-iframe'].forEach(id => { const 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) {17 行未改动 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) {2 行未改动 } 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(); ['lgsinlg-paste-iframe', 'lgsinlg-article-iframe'].forEach(id => { const el = document.getElementById(id); if (el) el.remove(); }); 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; }20 行未改动 }; check(); }
// ==================== 路由监听 ==================== const observer = new MutationObserver(() => { if (pending || window.__LGSinLG_active) return; const newPath = location.pathname; if (newPath !== currentPath) {11 行未改动 else observer.observe(document.body, { childList: true, subtree: true });
window.addEventListener('popstate', () => { console.log('[LGSinLG] popstate 触发,新路径:', location.pathname); if (document.getElementById('lgsinlg-error')?.style.display !== 'none') { 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);18 行未改动