跳到正文

科技·工程

洛谷增强插件

#SUSPENDED#约 57 分钟
原文

这是 2026年8月5日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年8月4日
收录
2026年8月5日
更新
2026年11月18日
篇幅
约 57 分钟
获赞
1

版本

  1. v3当前
  2. v2
  3. v1

简介

一个集广告屏蔽、题目着色、用户颜色、保存站跳转于一体的 Chrome 扩展 / Tampermonkey 插件。

背景

无意间看到了realskc的文章,但是年代久远,洛谷前端更新后许多功能已无法使用。于是我对这个插件进行了改造升级,最新版为3.0.0。

代码由 DeepSeek AI 辅助生成,经过手工测试与调整。

功能

屏蔽广告

自动移除洛谷页面上的推荐广告(div[data-v-ce0b4304] 中包含“洛谷推荐”的元素)。

显示题目颜色

插件将所有以题目编号开头的链接按难度自动着色

无论是讨论区、犇犇、题单还是个人主页的练习记录,只要是题目链接都会被着色。

根据咕值显示用户颜色

插件通过洛谷官方 API 获取用户信息并正确渲染颜色。修复了棕名用户(作弊者)显示为灰色的问题,现在作弊者会正确显示为棕色。

保存站自动跳转

当访问到无法查看的内容(如被删除的讨论、需要登录的剪贴板等)时,插件自动跳转到洛谷保存站 luogu.me。

可视化设置面板

通过油猴菜单或扩展图标可以打开设置面板,自由开关各个功能,无需修改代码。

原理

广告屏蔽:移除洛谷页面上的div[data-v-ce0b4304] 中包含“洛谷推荐”的元素。

题目颜色:已通过的题目直接从页面上的 .difficulty 标签读取背景色;尝试过的题目优先从 _feInstance 缓存读取,取不到再通过 fetch 请求;记录页同样优先读取缓存。其他页面(讨论区、犇犇)通过 fetch 请求题目页面,正则匹配 "difficulty":\d。请求限制为同时最多 22 个、间隔 200200 ms,防止429。

用户颜色:通过洛谷官方 API https://www.luogu.com.cn/api/user/search?keyword={uid} 获取用户信息,将 color 字段映射为 CSS 颜色。

安装

方法一:Chrome 扩展(crx 文件)

由于非官方扩展无法直接拖拽安装,需要通过组策略强制安装。

插件已打包为 crx 文件,点击下方链接下载:

安装步骤:

  1. 打开 Chrome,在地址栏输入 chrome://extensions/ 并回车。
  2. 开启右上角的「开发者模式」。
  3. 将 crx 文件拖入页面,Chrome 会提示无法安装,此时在页面上可以看到该扩展的 ID(一串字母),复制下来。
  4. 按下 Win+R,输入 gpedit.msc 打开本地组策略编辑器。
  5. 依次点击「计算机配置 → 管理模板」,右键选择「添加/删除模板」,导入 chrome.adm 文件。
  6. 找到路径「经典管理模板(ADM) → Google → Google Chrome → 扩展程序」。
  7. 双击「配置扩展程序安装许可名单」,选择「已启用」,点击「显示」。
  8. 将刚才复制的 ID 填入白名单列表,点击「应用」并按「确定」键关闭。
  9. 点击浏览器右上角的洛谷增强插件图标,点击「打开插件设置」,即可选择需要的功能(默认全开),点击保存并刷新页面即可。

如需更新插件,只需直接将crx文件拖入即可,无需进入本地组策略编辑器

方法二:Tampermonkey(油猴)

  1. 安装 Tampermonkey 浏览器扩展。
  2. 点击 Tampermonkey 图标 →「添加新脚本」。
  3. 将下方代码粘贴进去,按 Ctrl+S 保存。
  4. 点击油猴图标,点击「打开插件设置」,保存并刷新页面即可生效。

代码

油猴版完整代码
JavaScript
// ==UserScript==
// @name         洛谷增强插件
// @namespace    http://tampermonkey.net/
// @version      3.0.0
// @description  洛谷增强插件:广告屏蔽、题目颜色、用户颜色、保存站跳转
// @author       realskc (modified) & linch & Vitamin_B
// @match        *://*.luogu.com/*
// @match        *://*.luogu.com.cn/*
// @grant        GM_registerMenuCommand
// @run-at       document-end
// ==/UserScript==

'use strict';

(function(){
    const featureDict = new Map([
        ['lgbot1RemoveAd', '屏蔽广告'],
        ['lgbot1AddProblemsColor', '显示题目颜色'],
        ['lgbot1ColorizeUsers', '根据咕值显示用户颜色'],
        ['lgbot1SaveSiteJump', '保存站自动跳转']
    ]);

    const problemDifficultyToColor = [
        [191, 191, 191],
        [254, 76, 97],
        [243, 156, 17],
        [255, 193, 22],
        [82, 196, 26],
        [19, 194, 194],
        [52, 152, 219],
        [157, 61, 207],
        [14, 29, 105]
    ];

    class ConcurrencyLimiter {
        constructor(concurrency, interval) {
            this.concurrency = concurrency;
            this.interval = interval;
            this.queue = [];
            this.running = 0;
            this.timer = null;
            this.jitter = () => Math.random() * 100;
        }
        push(task) {
            return new Promise((resolve, reject) => {
                this.queue.push({ task, resolve, reject });
                this._next();
            });
        }
        _next() {
            if (this.running >= this.concurrency || this.queue.length === 0) return;
            const { task, resolve, reject } = this.queue.shift();
            this.running++;
            const delay = this.interval + this.jitter();
            setTimeout(() => {
                task().then(resolve).catch(reject).finally(() => {
                    this.running--;
                    if (this.timer) clearTimeout(this.timer);
                    this.timer = setTimeout(() => { this._next(); this.timer = null; }, this.interval);
                });
            }, delay);
            if (this.running < this.concurrency && this.queue.length > 0) {
                setTimeout(() => this._next(), 0);
            }
        }
    }

    function openSettings() {
        const old = document.getElementById('lgbot-settings-modal');
        if (old) old.remove();

        const keys = Array.from(featureDict.keys());
        const checkboxesHtml = keys.map(key => `
            <div style="margin:8px 0;">
                <label><input type="checkbox" id="${key}" /> ${featureDict.get(key)}</label>
            </div>
        `).join('');

        const overlay = document.createElement('div');
        overlay.id = 'lgbot-settings-modal';
        overlay.style.cssText = `
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 10000;
            display: flex;
            justify-content: center;
            align-items: center;
        `;
        overlay.addEventListener('click', (e) => { if (e.target === overlay) overlay.remove(); });

        const box = document.createElement('div');
        box.style.cssText = `
            background: white;
            padding: 20px;
            border-radius: 8px;
            max-width: 450px;
            width: 90%;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
            max-height: 80vh;
            overflow-y: auto;
            font-family: sans-serif;
        `;

        box.innerHTML = `
            <h3 style="margin-top:0;">插件功能设置</h3>
            ${checkboxesHtml}
            <div style="margin-top:20px; display:flex; flex-wrap:wrap; gap:8px;">
                <button class="lgbot-btn" data-action="save">保存</button>
                <button class="lgbot-btn" data-action="selectAll">全选</button>
                <button class="lgbot-btn" data-action="deselectAll">全不选</button>
                <button class="lgbot-btn" data-action="resetDefault">重置默认</button>
            </div>
            <div id="statusMsg" style="margin-top:15px; font-weight:bold; color:#28a745;"></div>
        `;

        const style = document.createElement('style');
        style.textContent = `
            .lgbot-btn {
                padding: 8px 18px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                color: #fff;
                background: #007bff;
            }
            .lgbot-btn:hover { background: #0069d9; }
            .lgbot-btn[data-action="selectAll"], .lgbot-btn[data-action="deselectAll"] {
                background: #6c757d;
            }
            .lgbot-btn[data-action="selectAll"]:hover,
            .lgbot-btn[data-action="deselectAll"]:hover {
                background: #5a6268;
            }
            .lgbot-btn[data-action="resetDefault"] {
                background: #ffc107;
                color: #000;
            }
            .lgbot-btn[data-action="resetDefault"]:hover {
                background: #e0a800;
            }
        `;
        box.appendChild(style);
        overlay.appendChild(box);
        document.body.appendChild(overlay);

        const getVal = (k) => { const v = localStorage.getItem(k); return v === null ? true : v === 'true'; };
        const setVal = (k, v) => localStorage.setItem(k, String(v));

        keys.forEach(k => {
            const cb = document.getElementById(k);
            if (cb) cb.checked = getVal(k);
        });

        box.querySelectorAll('.lgbot-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const action = btn.dataset.action;
                const status = document.getElementById('statusMsg');
                if (action === 'save') {
                    keys.forEach(k => setVal(k, document.getElementById(k).checked));
                    status.textContent = '已保存,刷新洛谷页面生效';
                    alert('设置已保存!请刷新洛谷页面以使更改生效。');
                } else if (action === 'selectAll') {
                    keys.forEach(k => { document.getElementById(k).checked = true; });
                } else if (action === 'deselectAll') {
                    keys.forEach(k => { document.getElementById(k).checked = false; });
                } else if (action === 'resetDefault') {
                    keys.forEach(k => {
                        document.getElementById(k).checked = true;
                        setVal(k, true);
                    });
                    status.textContent = '已重置为全部开启';
                    alert('已重置为全部开启!请刷新洛谷页面。');
                }
            });
        });
    }

    GM_registerMenuCommand('打开插件设置', openSettings);

    function removeAd() {
        const allDivs = document.querySelectorAll('div[data-v-ce0b4304]');
        let adElement = null;
        for (const div of allDivs) {
            if (div.innerText.includes('洛谷推荐') && div.querySelector('button.close')) {
                adElement = div;
                break;
            }
        }
        if (!adElement) adElement = document.querySelector('div[data-v-ce0b4304][data-v-097edf1f]');
        if (!adElement) adElement = document.querySelector('a[data-v-12b24cc3][data-v-ce0b4304]');
        if (adElement) { adElement.remove(); console.log('洛谷增强插件: 广告已移除'); return true; }
        return false;
    }

    function watchAdRemoval() {
        removeAd();
        const observer = new MutationObserver(() => removeAd());
        observer.observe(document.body, { childList: true, subtree: true });
        window.__lgbotAdObserver = observer;
    }

    const problemToColorMap = new Map();
    const problemFetcher = new ConcurrencyLimiter(2, 200);

    function getDifficultyColor(difficulty) {
        if (difficulty === undefined || difficulty === null) difficulty = 0;
        if (difficulty < 0) difficulty = 0;
        if (difficulty > 8) difficulty = 8;
        return `rgb(${problemDifficultyToColor[difficulty].join(',')})`;
    }

    function colorizePracticePageFromLabels() {
        const groups = document.querySelectorAll('.difficulty');
        let count = 0;
        groups.forEach(group => {
            const span = group.querySelector('span[style*="background-color"]');
            if (!span) return;
            const bgColor = span.style.backgroundColor;
            let problems = group.nextElementSibling;
            while (problems && !problems.matches('.problems')) {
                problems = problems.nextElementSibling;
            }
            if (!problems) return;
            const links = problems.querySelectorAll('a[href^="/problem/"]');
            links.forEach(link => {
                const pidSpan = link.querySelector('.pid');
                if (pidSpan && pidSpan.dataset.lgbotProblemColored !== '1') {
                    pidSpan.style.color = bgColor;
                    pidSpan.dataset.lgbotProblemColored = '1';
                    count++;
                } else if (!pidSpan) {
                    const text = link.innerText.trim();
                    const match = text.match(/^([A-Z]+\d+)/);
                    if (match) {
                        const pid = match[1];
                        if (link.dataset.lgbotProblemColored !== '1') {
                            link.innerHTML = text.replace(pid, `<span style="color:${bgColor};">${pid}</span>`);
                            link.dataset.lgbotProblemColored = '1';
                            count++;
                        }
                    }
                }
            });
        });
        if (count > 0) console.log(`洛谷增强插件: 练习页已为 ${count} 个题目编号着色(从难度标签)`);
        return count;
    }

    async function colorizePracticePageWithoutLabels() {
        const problemBlocks = document.querySelectorAll('.problems');
        let count = 0;
        let submittedMap = new Map();
        try {
            const feData = window._feInjection || window._feInstance;
            if (feData && feData.currentData) {
                const data = feData.currentData;
                if (data.submittedProblems) {
                    for (const p of data.submittedProblems) {
                        submittedMap.set(p.pid, getDifficultyColor(p.difficulty));
                    }
                }
                if (data.passedProblems) {
                    for (const p of data.passedProblems) {
                        submittedMap.set(p.pid, getDifficultyColor(p.difficulty));
                    }
                }
            }
        } catch(e) {}

        for (const block of problemBlocks) {
            const prev = block.previousElementSibling;
            if (prev && prev.matches('.difficulty')) continue;

            const links = block.querySelectorAll('a[href^="/problem/"]:not([data-lgbot-problem-colored="1"])');
            if (links.length === 0) continue;

            for (const link of links) {
                let problemid = link.href.split('/problem/')[1].split('?')[0].split('/')[0];
                if (!problemid || !/[a-zA-Z]/.test(problemid) || !/[0-9]/.test(problemid)) continue;
                let color = submittedMap.get(problemid);
                if (!color) color = await fetchProblemColorForLink(problemid);
                if (!color) continue;
                const pidSpan = link.querySelector('.pid');
                if (pidSpan) {
                    pidSpan.style.color = color;
                    pidSpan.dataset.lgbotProblemColored = '1';
                    count++;
                } else {
                    const text = link.innerText.trim();
                    const match = text.match(/^([A-Z]+\d+)/);
                    if (match && match[1] === problemid) {
                        link.innerHTML = text.replace(problemid, `<span style="color:${color};">${problemid}</span>`);
                        link.dataset.lgbotProblemColored = '1';
                        count++;
                    }
                }
            }
        }
        if (count > 0) console.log(`洛谷增强插件: 练习页已为 ${count} 个题目编号着色(通过缓存/请求)`);
    }

    async function colorizeRecordPage() {
        const links = document.querySelectorAll('a[href^="/problem/"]:not([data-lgbot-problem-colored="1"])');
        if (links.length === 0) return;

        let recordMap = new Map();
        try {
            const feData = window._feInjection || window._feInstance;
            if (feData && feData.currentData && feData.currentData.records) {
                const records = feData.currentData.records.result;
                if (records && records.length > 0) {
                    for (const item of records) {
                        if (item.problem && item.problem.pid) {
                            recordMap.set(item.problem.pid, getDifficultyColor(item.problem.difficulty));
                        }
                    }
                }
            }
        } catch(e) {}

        let count = 0;
        for (const link of links) {
            let problemid = link.href.split('/problem/')[1].split('?')[0].split('/')[0];
            if (!problemid || !/[a-zA-Z]/.test(problemid) || !/[0-9]/.test(problemid)) continue;
            let color = recordMap.get(problemid);
            if (!color) color = await fetchProblemColorForLink(problemid);
            if (!color) continue;
            const pidSpan = link.querySelector('.pid');
            if (pidSpan) {
                pidSpan.style.color = color;
                pidSpan.dataset.lgbotProblemColored = '1';
                count++;
            } else {
                const text = link.innerText.trim();
                const match = text.match(/^([A-Z]+\d+)/);
                if (match && match[1] === problemid) {
                    link.innerHTML = text.replace(problemid, `<span style="color:${color};">${problemid}</span>`);
                    link.dataset.lgbotProblemColored = '1';
                    count++;
                }
            }
        }
        if (count > 0) console.log(`洛谷增强插件: 记录页已为 ${count} 个题目编号着色`);
    }

    async function fetchProblemColorForLink(problemid) {
        if (problemToColorMap.has(problemid)) return problemToColorMap.get(problemid);
        const url = '/problem/' + problemid;
        try {
            const html = await problemFetcher.push(() =>
                fetch(url, {
                    credentials: 'include',
                    headers: { 'User-Agent': navigator.userAgent }
                }).then(r => {
                    if (!r.ok) throw new Error(`HTTP ${r.status}`);
                    return r.text();
                })
            );
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            let scriptText = '';
            for (const i of doc.querySelectorAll("script")) scriptText += i.textContent;
            const match = scriptText.match(/"difficulty":\d/);
            if (!match) return null;
            const difficulty = Number(match[0].match(/\d/)[0]);
            const color = getDifficultyColor(difficulty);
            problemToColorMap.set(problemid, color);
            return color;
        } catch (error) {
            console.warn(`获取题目 ${problemid} 颜色失败:`, error.message);
            return null;
        }
    }

    function isProblemId(problemid) {
        if (problemid.startsWith('AT_')) return true;
        if (!/[a-zA-Z]/.test(problemid) || !/[0-9]/.test(problemid)) return false;
        if (problemid.includes('html') || problemid.includes('void') || problemid.length > 20) return false;
        return true;
    }

    let scanTimer = null;

    function startPeriodicScan(scanFn, interval = 200) {
        if (scanTimer) clearInterval(scanTimer);
        scanTimer = setInterval(() => {
            if (!document.hidden) {
                scanFn();
            }
        }, interval);
        window.addEventListener('beforeunload', () => {
            if (scanTimer) clearInterval(scanTimer);
        });
    }

    async function scanAllLinks() {
        const allLinks = document.querySelectorAll('a[href*="/problem/"], a[href*="forum="]');
        const toProcess = [];
        for (const link of allLinks) {
            let problemid = null;
            const href = link.href;
            if (href.includes('/problem/')) {
                problemid = href.split('/problem/')[1].split('?')[0].split('/')[0];
            } else if (href.includes('forum=')) {
                const match = href.match(/forum=([^&]+)/);
                if (match) problemid = match[1];
            }
            if (!problemid || !isProblemId(problemid)) continue;

            const pidSpan = link.querySelector('.pid');
            if (pidSpan && pidSpan.dataset.lgbotProblemColored === '1') continue;
            if (!pidSpan && link.dataset.lgbotProblemColored === '1') continue;

            const text = link.innerText.trim();
            if (!pidSpan && !text.startsWith(problemid)) continue;

            toProcess.push({ link, pidSpan, problemid });
        }
        if (toProcess.length > 0) {
            for (const { link, pidSpan, problemid } of toProcess) {
                const color = await fetchProblemColorForLink(problemid);
                if (!color) continue;
                if (pidSpan) {
                    pidSpan.style.color = color;
                    pidSpan.dataset.lgbotProblemColored = '1';
                } else {
                    const text = link.innerText.trim();
                    if (text.startsWith(problemid)) {
                        link.innerHTML = text.replace(problemid, `<span style="color:${color};">${problemid}</span>`);
                        link.dataset.lgbotProblemColored = '1';
                    }
                }
            }
            console.log(`洛谷增强插件: 已处理 ${toProcess.length} 个题目编号`);
        }

        await colorizeAllUserLinks();
    }

    async function addProblemsColor() {
        const path = window.location.pathname;
        if (path.match(/^\/user\/\d+\/practice/)) {
            colorizePracticePageFromLabels();
            await colorizePracticePageWithoutLabels();
            setTimeout(() => {
                colorizePracticePageFromLabels();
                colorizePracticePageWithoutLabels();
            }, 300);
            const observer = new MutationObserver(() => {
                colorizePracticePageFromLabels();
                colorizePracticePageWithoutLabels();
            });
            observer.observe(document.body, { childList: true, subtree: true });
            window.__lgbotProblemObserver = observer;
            startPeriodicScan(() => {
                colorizePracticePageFromLabels();
                colorizePracticePageWithoutLabels();
            }, 200);
            return;
        }
        if (path.startsWith('/record/list')) {
            await colorizeRecordPage();
            const observer = new MutationObserver(() => {
                colorizeRecordPage();
            });
            observer.observe(document.body, { childList: true, subtree: true });
            window.__lgbotProblemObserver = observer;
            startPeriodicScan(colorizeRecordPage, 200);
            return;
        }
        await scanAllLinks();
        startPeriodicScan(scanAllLinks, 200);

        const observer = new MutationObserver(() => {
            scanAllLinks();
        });
        observer.observe(document, { childList: true, subtree: true, characterData: true });
        window.__lgbotProblemObserver = observer;
    }

    const userColorCache = new Map();
    const userFetcher = new ConcurrencyLimiter(3, 200);

    function mapApiColorToCss(apiColor) {
        if (!apiColor) return '#bbb';
        const lower = apiColor.toLowerCase();
        const map = {
            'gray': '#bbb', 'grey': '#bbb',
            'blue': '#0e90d2',
            'green': '#5eb95e',
            'orange': '#e67e22',
            'red': '#e74c3c',
            'purple': '#8e44ad',
            'brown': '#ad8b00',
            'cheater': '#ad8b00'
        };
        return map[lower] || '#bbb';
    }

    async function fetchUserInfo(uid) {
        if (userColorCache.has(uid)) return userColorCache.get(uid);
        const apiUrl = `https://www.luogu.com.cn/api/user/search?keyword=${uid}`;
        try {
            const response = await fetch(apiUrl, {
                credentials: 'include',
                headers: {
                    'User-Agent': navigator.userAgent,
                    'Accept': 'application/json'
                }
            });
            if (!response.ok) throw new Error(`HTTP ${response.status}`);
            const data = await response.json();
            if (data.users && data.users.length > 0) {
                const user = data.users[0];
                let cssColor = user.isAdmin ? '#8e44ad' : mapApiColorToCss(user.color);
                const info = { color: cssColor };
                userColorCache.set(uid, info);
                return info;
            }
        } catch (error) {
            console.warn(`获取用户 ${uid} 颜色失败:`, error.message);
        }
        return null;
    }

    // ---------- 修改点 1:删除正则限制;修改点 2:支持绝对路径 ----------
    async function colorizeUserLink(link) {
        const href = link.getAttribute('href');
        // 提取路径部分(去掉域名)
        const path = href.replace(/^https?:\/\/[^\/]+/, '');
        if (!/^\/user\/\d+$/.test(path)) return;

        const text = link.innerText.trim();
        const navTexts = ['个人中心', '主页', '用户设置', '练习情况', '练习', '专栏', '我/TA 关注的人', '个人设置', '我的收藏', '我的团队', '我的比赛', '我的题库'];
        if (navTexts.some(t => text === t || text.includes(t))) return;
        // 原正则已删除,现在不限制字符类型

        const match = path.match(/\/user\/(\d+)/);
        if (!match) return;
        const uid = match[1];
        const info = await userFetcher.push(() => fetchUserInfo(uid));
        if (info) {
            link.style.setProperty('color', info.color, 'important');
        }
        link.dataset.lgbotColored = '1';
    }

    async function colorizeAllUserLinks() {
        const allLinks = document.querySelectorAll('a[href^="/user/"], a[href*="luogu.com/user/"], a[href*="luogu.com.cn/user/"]');
        const promises = [];
        for (const link of allLinks) {
            if (link.dataset.lgbotColored === '1') continue;
            const href = link.getAttribute('href');
            const path = href.replace(/^https?:\/\/[^\/]+/, '');
            if (/^\/user\/\d+$/.test(path)) {
                promises.push(colorizeUserLink(link));
            }
        }
        await Promise.all(promises);
        const colored = document.querySelectorAll('a[href^="/user/"][data-lgbot-colored="1"]').length;
        if (colored > 0) console.log(`洛谷增强插件: 已为 ${colored} 个用户链接上色`);
    }

    function watchUserColors() {
        colorizeAllUserLinks();
        let timeoutId = null;
        const observer = new MutationObserver(() => {
            if (timeoutId) clearTimeout(timeoutId);
            timeoutId = setTimeout(() => {
                colorizeAllUserLinks();
                timeoutId = null;
            }, 500);
        });
        observer.observe(document.body, {
            childList: true,
            subtree: true,
            attributes: false,
            characterData: false
        });
        window.__lgbotUserColorObserver = observer;
    }

    function saveSiteJump() {
        const url = window.location.href;
        const title = document.title;
        const html = document.documentElement.outerHTML;

        const isError = title.indexOf('cannot serve content') >= 0;
        const isDeleted = html.indexOf('该内容已删除') >= 0;
        const isLogin = html.indexOf('请先登录') >= 0;
        const isVerify = html.indexOf('完成实名验证才能查看') >= 0;
        const isDiscussBlock = html.indexOf('题目讨论版需要有提交才能查看') >= 0;
        const isSecurityCenter = title.indexOf('安全访问中心 - 洛谷') >= 0;

        if (isError && (url.includes('/paste/') || url.includes('/article/'))) {
            const newUrl = url.replace('.com', '.me');
            console.log('洛谷增强插件: 跳转至保存站 (云剪切板/专栏) ->', newUrl);
            window.location.replace(newUrl);
            return;
        }

        if (isDeleted || isLogin || isVerify || isDiscussBlock) {
            const match = url.match(/\/discuss\/(\d+)/);
            if (match) {
                const postId = match[1];
                const newUrl = `https://luogu.me/discuss/${postId}`;
                console.log('洛谷增强插件: 跳转至讨论区保存站 ->', newUrl);
                window.location.replace(newUrl);
                return;
            }
        }

        if (isSecurityCenter && url.includes('.cn')) {
            const newUrl = url.replace('.cn', '');
            console.log('洛谷增强插件: 跳转至国际站(避开安全中心) ->', newUrl);
            window.location.replace(newUrl);
            return;
        }

        if (isError && !url.includes('/paste/') && !url.includes('/article/')) {
            if (url.includes('.com.cn')) {
                const newUrl = url.replace('.com.cn', '.com');
                console.log('洛谷增强插件: 跳转至国际站 ->', newUrl);
                window.location.replace(newUrl);
            } else if (url.includes('.com')) {
                const newUrl = url.replace('.com', '.me');
                console.log('洛谷增强插件: 跳转至保存站 (.me) ->', newUrl);
                window.location.replace(newUrl);
            }
            return;
        }
    }

    if (localStorage.getItem('lgbot1SaveSiteJump') !== 'false') {
        if (window.location.pathname.match(/^\/(paste|article|discuss)\//)) {
            saveSiteJump();
        }
    }

    if (localStorage.getItem('lgbot1RemoveAd') !== 'false') watchAdRemoval();
    if (localStorage.getItem('lgbot1AddProblemsColor') !== 'false') {
        if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => setTimeout(addProblemsColor, 200));
        else setTimeout(addProblemsColor, 200);
    }
    if (localStorage.getItem('lgbot1ColorizeUsers') !== 'false') {
        if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', watchUserColors);
        else watchUserColors();
    }
})();

更新日志

v3.0.0(2026-08-05)

  • 修复棕名用户(作弊者)显示为灰色的问题。
  • 题目颜色优先从 _feInstance 缓存读取,减少请求。
  • 修复日文用户名或用户链接采用绝对路径无法上色的问题。

附件

文件链接
洛谷增强插件.crx下载
chrome.adm下载

说明

本文在写作过程中使用了 DeepSeek AI 进行代码生成、文字辅助润色和格式修改。所有代码均经过手工测试与验证,保证作者对文章的贡献大于AI。

提示

脚本题目颜色与用户颜色抓取速度较慢属正常现象,防止请求频率过高导致429错误,请不要将并发数和间隔设置过快,由此产生的一切后果请自行负责!