logo AlgoBeat OnlineJudge
登录 注册

ABOJ Better

Carey_chen HCl 2026-09-12 12:21:25 2026-09-16 21:54:01

声明:本脚本与 ABOI 管理组没有任何关联。本文内容以及所有代码均可视为自由软件。

本脚本大部分由 Deepseek AI 编写。
这是一个修复了一些错误,并添加了一些方便功能的脚本。

建议结合 https://github.com/tonsky/FiraCode 食用。

本脚本少量请求了洛谷 API 用于搜索对应题面,但绝对不会使用 Cookie ,绝对不会读取任何除题面以外的信息。
请求频率与你访问 ABOJ 的频率完全相同且有缓存。如果没有大量请求 ABOJ 页面,几乎不可能被洛谷封号。

// ==UserScript==
// @name         ABOJ Better
// @namespace    https://algobeat.online/
// @version      1.0.0
// @description  ABOJ 增强合集
// @author       Deepseek AI
// @match        https://www.luogu.com.cn/problem/P*
// @match        https://algobeat.online/*
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// @connect      algobeat.online
// @connect      www.luogu.com.cn
// @run-at       document-begin
// ==/UserScript==

(function () {
    'use strict';

    const HOST = location.hostname;

    /* ============================================================
     * 1. ABOJ:Fira Code 字体 + 注销 → 登出
     * ============================================================ */
    if (HOST === 'algobeat.online') {
        GM_addStyle(`body, div, p, span, a, li, h1, h2, h3, h4, h5, h6, td, th, label, input, textarea, button, select, option {font-family: Fira, sans-serif !important;}.ui.items > .item {display: block !important;}`);

        function fixLogout() {
            document.querySelectorAll('a.item[href-post*="/logout"]').forEach(a => {
                a.childNodes.forEach(n => {
                    if (n.nodeType === 3 && n.nodeValue.includes('注销'))
                        n.nodeValue = n.nodeValue.replace('注销', '登出');
                });
            });
        }
        fixLogout();
        new MutationObserver(fixLogout).observe(document.body, { childList: true, subtree: true });
    }

    /* ============================================================
     * 2. 洛谷 P 题 → ABOJ 智能跳转
     * ============================================================ */
    if (/^www\.luogu\.com\.cn$/.test(HOST) && /\/problem\/P\d+/i.test(location.pathname)) {
        function getPid() {
            const m = location.pathname.match(/\/problem\/(P\d+)/i);
            return m ? m[1].toUpperCase() : null;
        }

        function getTitle(pid) {
            const h2 = document.querySelector('h2.title.lfe-h2');
            if (!h2) return null;
            return h2.textContent.trim().replace(new RegExp('^' + pid + '\\s+', 'i'), '').trim();
        }

        function getCard() {
            for (const card of document.querySelectorAll('.l-card')) {
                for (const span of card.querySelectorAll('span')) {
                    if (span.textContent.trim() === '题目编号') return card;
                }
            }
            return null;
        }

        function getFirstRow(card) { return card.querySelector('.l-flex-info-row'); }

        function findHistoryRow(card) {
            return Array.from(card.children).find(el =>
                el.classList && el.classList.contains('l-flex-info-row') &&
                el.querySelector(':scope > span')?.textContent.trim() === '历史分数'
            );
        }

        function copyDataV(src, tgt) {
            if (!src || !tgt) return;
            for (const attr of src.attributes) {
                if (attr.name.startsWith('data-v-')) tgt.setAttribute(attr.name, attr.value);
            }
        }

        function removeExistingAbojLink(card) {
            card.querySelectorAll('a[href*="algobeat.online/problem/"]').forEach(link => {
                if (!link.closest('[data-aboj-pid]')) {
                    link.closest('.l-flex-info-row')?.remove();
                }
            });
        }

        function createRow(pid, firstRow) {
            const row = document.createElement('div');
            row.className = 'l-flex-info-row';
            row.setAttribute('data-aboj-pid', pid);
            copyDataV(firstRow, row);

            const label = document.createElement('span');
            label.textContent = '跳转';
            const firstLabel = firstRow.querySelector(':scope > span');
            if (firstLabel) copyDataV(firstLabel, label);

            const content = document.createElement('span');
            content.className = 'aboj-content';
            copyDataV(firstRow, content);

            row.appendChild(label);
            row.appendChild(content);
            return row;
        }

        function setLoading(row) {
            const content = row.querySelector('.aboj-content');
            if (!content) return;
            content.innerHTML = '';
            const span = document.createElement('span');
            span.style.fontWeight = 'bold';
            span.textContent = '加载中...';
            copyDataV(row.querySelector(':scope > span'), span);
            content.appendChild(span);
        }

        function updateRowContent(row, found, abojUrl) {
            const content = row.querySelector('.aboj-content');
            if (!content) return;
            content.innerHTML = '';

            if (found) {
                const link = document.createElement('a');
                link.href = abojUrl;
                link.target = '_blank';
                link.rel = 'noopener noreferrer';
                const anyLink = document.querySelector('.l-card a');
                if (anyLink) copyDataV(anyLink, link);

                const span = document.createElement('span');
                span.className = 'lcolor--bule-3';
                span.style.fontWeight = 'bold';
                span.style.color = 'var(--lfe-color--blue-3, #3498db)';
                span.textContent = 'AlgoBeat';
                if (anyLink?.querySelector('span')) copyDataV(anyLink.querySelector('span'), span);
                link.appendChild(span);
                content.appendChild(link);
            } else {
                const span = document.createElement('span');
                span.style.fontWeight = 'bold';
                span.textContent = '未找到';
                copyDataV(row.querySelector(':scope > span'), span);
                content.appendChild(span);
            }
        }

        const pidCache = {};

        function process(pid) {
            const title = getTitle(pid);
            if (!title) return;
            const card = getCard();
            if (!card) return;
            const firstRow = getFirstRow(card);
            if (!firstRow) return;

            removeExistingAbojLink(card);

            let row = card.querySelector(`[data-aboj-pid="${pid}"]`);
            if (!row) {
                row = createRow(pid, firstRow);
                const historyRow = findHistoryRow(card);
                if (historyRow?.nextSibling) card.insertBefore(row, historyRow.nextSibling);
                else if (historyRow) card.appendChild(row);
                else card.appendChild(row);
            }

            if (pidCache[pid]) return updateRowContent(row, pidCache[pid].found, pidCache[pid].url);
            if (row.dataset.loading === 'true') return;

            setLoading(row);
            row.dataset.loading = 'true';

            const searchUrl = 'https://algobeat.online/api/v2/search/problems/' +
                encodeURIComponent(title) + '?_=' + Date.now();

            GM_xmlhttpRequest({
                method: 'GET',
                url: searchUrl,
                headers: {
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                onload: function (response) {
                    let found = false, url = null;
                    try {
                        const data = JSON.parse(response.responseText);
                        if (data.success && Array.isArray(data.results)) {
                            for (const item of data.results) {
                                if (item.value >= 200000 && item.value <= 299999) {
                                    const nameTitle = item.name.replace(/^#\d+\.\s*/, '').trim();
                                    if (nameTitle === title.trim()) {
                                        found = true;
                                        url = 'https://algobeat.online' + item.url;
                                        break;
                                    }
                                }
                            }
                        }
                    } catch (e) { found = false; }

                    pidCache[pid] = { found, url };
                    if (getPid() === pid) {
                        const currentRow = getCard()?.querySelector(`[data-aboj-pid="${pid}"]`);
                        if (currentRow) updateRowContent(currentRow, found, url);
                    }
                },
                onerror: function () {
                    pidCache[pid] = { found: false, url: null };
                    if (getPid() === pid) {
                        const currentRow = getCard()?.querySelector(`[data-aboj-pid="${pid}"]`);
                        if (currentRow) updateRowContent(currentRow, false, null);
                    }
                }
            });
        }

        let lastPid = null;
        setInterval(() => {
            const pid = getPid();
            if (pid && pid !== lastPid) {
                lastPid = pid;
                setTimeout(() => process(pid), 0);
            } else if (pid) {
                const card = getCard();
                if (card && !card.querySelector(`[data-aboj-pid="${pid}"]`) && !pidCache[pid]) process(pid);
            }
        }, 1000);
    }

    /* ============================================================
     * 3. ABOJ 题目页 → 洛谷跳转
     * ============================================================ */
    if (HOST === 'algobeat.online' && /^\/problem\/2\d{5}$/.test(location.pathname)) {
        function getProblemId() {
            const m = location.pathname.match(/\/problem\/(\d+)/);
            return m ? m[1] : null;
        }

        function getTitle() {
            const selectors = ['h1.ui.header', 'h1.header', '.problem-header h1', '.problem-title', '#problem-title', 'h1'];
            for (const sel of selectors) {
                const el = document.querySelector(sel);
                if (el?.textContent.trim()) {
                    let text = el.textContent.trim().replace(/^#\d+\.\s*/, '').trim();
                    if (text) return text;
                }
            }
            return null;
        }

        function getOrCreateJumpButton(problemId) {
            const existingBtn = Array.from(document.querySelectorAll('.ui.buttons a'))
                .find(a => a.textContent.trim() === '跳转洛谷');
            if (existingBtn) return existingBtn;

            const solutionBtn = document.querySelector(`.ui.buttons a[href="/problem/${problemId}/solutions"]`);
            if (solutionBtn?.parentElement) {
                const btn = document.createElement('a');
                btn.className = 'small ui purple button';
                btn.textContent = '跳转洛谷';
                btn.target = '_blank';
                btn.rel = 'noopener noreferrer';
                solutionBtn.insertAdjacentElement('afterend', btn);
                return btn;
            }

            const btnGroup = document.querySelector('.ui.buttons');
            if (btnGroup) {
                const btn = document.createElement('a');
                btn.className = 'small ui purple button';
                btn.textContent = '跳转洛谷';
                btn.target = '_blank';
                btn.rel = 'noopener noreferrer';
                btnGroup.appendChild(btn);
                return btn;
            }
            return null;
        }

        function updateButton(btn, pid) {
            if (!btn) return;
            btn.href = `https://www.luogu.com.cn/problem/${pid}`;
            btn.classList.add('small', 'ui', 'purple', 'button');
            btn.textContent = '跳转洛谷';
            btn.target = '_blank';
            btn.rel = 'noopener noreferrer';
        }

        function getCache(problemId) {
            try {
                const val = localStorage.getItem(`aboj2luogu_${problemId}`);
                return val ? JSON.parse(val)?.pid : null;
            } catch (e) { return null; }
        }

        function setCache(problemId, pid) {
            try { localStorage.setItem(`aboj2luogu_${problemId}`, JSON.stringify({ pid })); } catch (e) {}
        }

        function processABOJToLuogu() {
            const problemId = getProblemId();
            if (!problemId) return;
            const title = getTitle();
            if (!title) return;

            const btn = getOrCreateJumpButton(problemId);
            if (!btn) return;
            if (btn.href && /luogu\.com\.cn\/problem\/P\d+/.test(btn.href)) return;

            const cachedPid = getCache(problemId);
            if (cachedPid) return updateButton(btn, cachedPid);

            const searchUrl = `https://www.luogu.com.cn/problem/list?type=all&keyword=${encodeURIComponent(title)}&page=1`;

            GM_xmlhttpRequest({
                method: 'GET',
                url: searchUrl,
                headers: {
                    'Accept': 'application/json, text/plain, */*',
                    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-Lentille-Request': 'content-only',
                },
                onload: function (response) {
                    if (response.status !== 200) return;
                    try {
                        const data = JSON.parse(response.responseText);
                        const results = data?.data?.problems?.result || [];
                        const lowerTitle = title.toLowerCase();
                        const match = results.find(p => p.type === 'P' && p.name.toLowerCase().includes(lowerTitle));
                        if (match?.pid) {
                            updateButton(btn, match.pid);
                            setCache(problemId, match.pid);
                        }
                    } catch (e) {}
                }
            });
        }

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => setTimeout(processABOJToLuogu, 500));
        } else {
            setTimeout(processABOJToLuogu, 500);
        }
    }
})();

共 5 条回复

TuanTuan_Cat

B 题库没有跳转,所以应该加一个

AlgoBeat 官方账号

qp

tyxx040105

方便水题解

Carey_chen HCl

@TuanTuan_Cat

使用了 Fira Code 连字符字体,需要到 Github 下载。如果觉得丑可以删除对应 css 代码。

TuanTuan_Cat

安装插件之后,代码框里面字体为什么变了