跳到正文

科技·工程

lg-fcker - 再也不怕被骗关啦 ✨

ygg_pls约 57 分钟
原文
文章信息与版本

文章信息

收录
2026年6月21日
更新
2026年6月28日
篇幅
约 57 分钟
获赞
2

版本

  1. v6当前
  2. v5
  3. v4
  4. v3
更早的 2 个版本
  1. v2
  2. v1

访问人数:

关注@ygg_pls,@Gary0谢谢!!!

upd on 2026.6.28:已更新到5.45.4版,支持一键回敬与回关,自定义badge。

badge在某些地方不会显示,而在主页疯狂显示,欢迎大佬提供修改神秘bug后的源代码

这是一个小插件,洛谷取关提醒器,可以快速(?慢速)检测近期有谁取关了你。感谢 @ygg_pls 提供的 Idea, @Gary0的代码!

follower-checker 简称 fcker。

JavaScript
// @name            lg-fcker - 洛谷取关提醒器
// @version         5.4
// @license         GNU GPLv3

安装方法

注意粉丝越多,需要向洛谷发送的请求越多。如果您的粉丝较多,插件会在短时间内向洛谷发送大量请求。所以不推荐粉丝数极多的网红使用。

鉴于查询时会向洛谷服务器发送大量请求,已将每日列表缓存以确保每日最多查询一次。

核心部分人工编写,部分 css 使用 Gemini, DS 辅助,好用就资瓷点赞关注一下吧。

代码
JavaScript
// ==UserScript==
// @name            lg-fcker - 洛谷取关提醒器(增强版)
// @namespace       http://tampermonkey.net/
// @version         5.4
// @description     洛谷取关提醒器,实时检测粉丝变化,支持回敬与回关;Badge 支持云端自定义样式(边框/颜色/流动等),仅管理员可配置。
// @author          Gary0 & ygg_pls
// @license         GNU GPLv3
// @run-at          document-end
// @match           https://www.luogu.com.cn/*
// @icon            https://cdn.luogu.com.cn/upload/usericon/3.png
// @grant           none
// ==/UserScript==

const version = "5.4", devs = [1202669, 1691170];
const BADGE_REFRESH_INTERVAL = 300000; // 5分钟

function esc_html(s) {
    let str = String(s);
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}
function get_el(id) { return document.getElementById(id); }
function new_el(id) { return document.createElement(id); }
function insert_el(base, label, content, id, class_list) {
    const el = new_el(label);
    el.innerHTML = content;
    el.id = id;
    el.className = class_list;
    return base.appendChild(el);
}
function insert_css(content) {
    insert_el(get_el("fcker"), "style", content, "", "");
}
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 解析云端数据(支持字符串或对象)
function parse_badge_data(raw) {
    try {
        const data = JSON.parse(raw);
        const map = new Map();
        for (const [key, value] of Object.entries(data)) {
            if (typeof value === 'string') {
                map.set(key, { text: value, style: '' });
            } else if (typeof value === 'object' && value !== null) {
                map.set(key, {
                    text: String(value.text || ''),
                    style: String(value.style || '')
                });
            }
        }
        return map;
    } catch {
        return new Map();
    }
}

function string_to_map(data_json) {
    try {
        const data_ob = JSON.parse(data_json);
        return new Map(Object.entries(data_ob));
    } catch { return new Map(); }
}
function map_to_string(data_map) {
    return JSON.stringify(Object.fromEntries(data_map));
}

async function update_relation(uid, action) {
    const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    if (!token) return false;
    try {
        const res = await fetch("https://www.luogu.com.cn/api/user/updateRelationShip", {
            method: "POST",
            headers: { "content-type": "application/json", "x-csrf-token": token, "x-requested-with": "XMLHttpRequest" },
            body: JSON.stringify({ uid: Number(uid), relationship: Number(action) })
        });
        return res.ok;
    } catch (e) { return false; }
}
function get_uid() {
    const m = document.getElementById("lentille-context");
    if (!m) return null;
    const json = JSON.parse(m.innerHTML);
    return json?.user?.uid || null;
}
const UID = get_uid();
if (!UID) {
    console.warn("lg-fcker: 未检测到登录用户,脚本停止。");
} else {
    const fcker = insert_el(document.body, "div", "", "fcker", "");
    fcker.style = "position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 1000; pointer-events: none;";
    insert_css(`
        .fcker-card {
            background-color: #fff;
            box-shadow: 0 1px 3px #1a1a1a1a;
            border-radius: 4px;
            padding: 10px;
            margin: 10px;
            text-align: center;
            overflow-y: auto;
        }
        .fcker-btn {
            background-color: #3498db;
            color: #fff;
            border: none;
            border-radius: 4px;
            padding: 10px;
            margin: 10px;
            text-align: center;
            cursor: pointer;
        }
        .fcker-btn:hover { opacity: 0.8; }
        .fcker-user {
            text-align: left;
            height: 42px;
            padding: 10px;
            overflow: hidden;
            white-space: nowrap;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .fcker-user-info {
            display: flex;
            align-items: center;
            overflow: hidden;
            white-space: nowrap;
            width: calc(100% - 90px);
            height: 100%;
        }
        .fcker-user .left {
            border-radius: 50%;
            height: 100%;
            vertical-align: middle;
        }
        .fcker-user .right {
            padding-left: 10px;
            display: inline-block;
            height: 100%;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            vertical-align: middle;
            width: calc(100% - 42px);
        }
        .fcker-user .user-title {
            display: flex;
            align-items: center;
            gap: 4px;
            height: 22px;
        }
        .fcker-user svg {
            display: inline-block;
            height: 1.1em;
            width: 1.125em;
            vertical-align: middle;
        }
        .fcker-user .am-badge {
            display: inline-block;
            padding: .25em .625em;
            font-size: 75%;
            font-weight: 700;
            line-height: 1;
            color: #fff;
            text-align: center;
            white-space: nowrap;
            vertical-align: baseline;
        }
        .fcker-user .am-radius { border-radius: 2px; }
        .fcker-user .slogan {
            font-size: .875em;
            color: #444;
            margin-top: 2px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
        .fcker-action-btn {
            border: none;
            border-radius: 4px;
            padding: 6px 10px;
            color: #fff;
            font-size: 11px;
            cursor: pointer;
            white-space: nowrap;
        }
        #fcker-main {
            position: fixed;
            top: 60px;
            right: -290px;
            width: 300px;
            pointer-events: auto;
            transition: transform 0.2s ease;
        }
        #fcker-main:hover { transform: translateX(-270px); }
        .fcker-modal-mask {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            pointer-events: auto;
            z-index: 1050;
        }
        .fcker-modal-dialog {
            background: #fff;
            border-radius: 4px;
            width: 550px;
            max-width: 90vw;
            height: 600px;
            max-height: 80vh;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            text-align: left;
        }
        .fcker-modal-header {
            padding: 14px 20px;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .fcker-modal-body {
            padding: 20px;
            flex: 1;
            overflow-y: auto;
        }
        .fcker-modal-close {
            background: none;
            border: none;
            font-size: 22px;
            color: #999;
            cursor: pointer;
            line-height: 1;
            padding: 0;
        }
        .fcker-modal-close:hover { color: #333; }

        /* 全局 Badge 样式(默认) */
        .fcker-global-badge {
            display: inline-block;
            padding: .25em .625em;
            font-size: 75%;
            font-weight: 700;
            line-height: 1;
            color: #fff;
            text-align: center;
            white-space: nowrap;
            vertical-align: baseline;
            border-radius: 2px;
            margin-left: 4px;
            background-color: #888; /* 默认背景,会被内联样式覆盖 */
        }

        /* 内置流动动画(管理员可调用) */
        @keyframes flow {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
    `);

    const main = insert_el(fcker, "div", "<h3>取关提醒器</h3>", "fcker-main", "fcker-card");
    const get_btn = insert_el(main, "button", "获取粉丝列表", "", "fcker-btn");
    const info_btn = insert_el(main, "button", "其他", "", "fcker-btn");

    function show_info() {
        main.style.display = "none";
        document.body.style.overflow = "hidden";
        const mask = insert_el(fcker, "div", "", "", "fcker-modal-mask");
        const dialog = insert_el(mask, "div", "", "", "fcker-modal-dialog");
        const header = insert_el(dialog, "div", "关于", "", "fcker-modal-header");
        const quit_btn = insert_el(header, "button", "×", "", "fcker-modal-close");
        function destroy_modal() {
            mask.remove();
            document.body.style.overflow = "";
            main.style.display = "";
        }
        quit_btn.addEventListener("click", destroy_modal);
        const html = `
            <h3>lg-fcker ${version}</h3>
            <p id="dev-1202669">By @<a href="https://www.luogu.com.cn/user/1202669">Gary0</a></p>
            <p id="dev-1691170">By @<a href="https://www.luogu.com.cn/user/1691170">ygg_pls</a></p>
            <p><h4>自定义 badge</h4>
            <a href="https://www.luogu.com.cn/chat?uid=1202669">私信 Gary0</a> 或 <a href="https://www.luogu.com.cn/chat?uid=1691170">私信 ygg_pls</a><br><br>
            <a href="https://www.luogu.com.cn/problem/U696560">云端储存库(样式配置)</a></p>
        `;
        insert_el(dialog, "div", html, "", "fcker-modal-body");
        for (const dev of devs) {
            const btn = insert_el(get_el(`dev-${dev}`), "button", "关注 ta", "", "fcker-action-btn");
            btn.style.backgroundColor = "#52c41a";
            btn.addEventListener("click", async () => {
                btn.disabled = true;
                btn.innerText = "...";
                btn.style.backgroundColor = "#bfbfbf";
                if (await update_relation(dev, 1)) btn.innerText = "已关注";
                else { btn.disabled = false; btn.innerText = "失败或已关注"; }
            });
        }
    }
    info_btn.addEventListener("click", show_info);

    // 获取云端 Badge 数据(解析为 Map<uid, {text, style}>)
    async function get_badges() {
        try {
            const resp = await fetch("https://www.luogu.com.cn/problem/U696560");
            const text = await resp.text();
            const m = text.match(/<script id="lentille-context" type="application\/json">([\s\S]*?)<\/script>/);
            if (!m) return new Map();
            const json = JSON.parse(m[1]);
            const raw = json?.data?.problem?.samples?.[0]?.[0];
            if (!raw) return new Map();
            // 使用 parse_badge_data 解析
            return parse_badge_data(raw);
        } catch {
            return new Map();
        }
    }

    async function parse_followers(html) {
        const m = html.match(/<script id="lentille-context" type="application\/json">([\s\S]*?)<\/script>/);
        if (!m) return null;
        try {
            const json = JSON.parse(m[1]);
            return json?.data?.users?.result || null;
        } catch { return null; }
    }
    async function parse_followers_count(html) {
        const m = html.match(/<script id="lentille-context" type="application\/json">([\s\S]*?)<\/script>/);
        if (!m) return null;
        try {
            const json = JSON.parse(m[1]);
            return json?.data?.users?.count || null;
        } catch { return null; }
    }

    async function get_followers(uid, page) {
        try {
            const resp = await fetch(`https://www.luogu.com.cn/user/${uid}/follower?page=${page}`);
            const text = await resp.text();
            const data = await parse_followers(text);
            return data ? { success: true, data } : { success: false, data: "解析失败" };
        } catch (err) {
            return { success: false, data: `请求失败: ${err}` };
        }
    }
    async function get_followers_count(uid) {
        try {
            const resp = await fetch(`https://www.luogu.com.cn/user/${uid}/follower`);
            const text = await resp.text();
            const count = await parse_followers_count(text);
            return count !== null ? { success: true, data: count } : { success: false, data: "解析失败" };
        } catch (err) {
            return { success: false, data: `请求失败: ${err}` };
        }
    }

    async function get_all_followers(uid, statusCallback) {
        const cdata = await get_followers_count(uid);
        if (!cdata.success) {
            statusCallback(cdata.data);
            return null;
        }
        const count = cdata.data;
        if (count > 800) {
            statusCallback("您的粉丝页数太多,为保障安全,禁止使用");
            return null;
        }
        const pages = Math.ceil(count / 20);
        let nc = 0, success = true, list = [];
        const tasks = [];
        statusCallback(`loading... 0 / ${count}`);
        for (let i = 1; i <= pages; i++) {
            await sleep(1000);
            const p = get_followers(uid, i).then(res => {
                if (res.success && success) {
                    nc += res.data.length;
                    list.push(...res.data);
                    statusCallback(`loading... ${nc} / ${count}`);
                } else if (!res.success) {
                    success = false;
                    statusCallback(res.data);
                }
            });
            tasks.push(p);
        }
        await Promise.all(tasks);
        if (success && nc === count) return list;
        statusCallback(success ? "获取数量不一致" : "获取失败");
        return null;
    }

    function get_color(color) {
        color = color.toLowerCase();
        if (color === "gray") return "var(--lfe-color--grey-3)";
        if (color === "cheater") return "var(--lfe-color--yellow-4)";
        return `var(--lfe-color--${color}-3)`;
    }

    function display_followers(container, list, action_type = "") {
        let badges = new Map();
        try {
            const raw = localStorage.getItem("fcker-badge");
            if (raw) badges = string_to_map(raw); // 注意:存储的是序列化后的 Map,我们需保留对象结构
            // 但由于之前存储的是 Map 序列化,需要处理,可能丢失对象。这里我们重新从云端解析以保证样式。
            // 为了安全,我们在 get_btn 点击时也调用了 refreshBadges,所以这里直接从本地缓存获取,但为支持样式,我们使用 getBadgeMap 获取完整配置。
            badges = getBadgeMap();
        } catch {}
        for (const user of list) {
            const uidStr = user.uid.toString();
            const badgeConfig = badges.get(uidStr);
            if (badgeConfig) {
                user.badge = user.badge ? user.badge + " || " + badgeConfig.text : badgeConfig.text;
                // 保存样式供后续显示使用(但 display_followers 中我们只显示文本,样式不在此处应用)
                // 为了简化,我们在粉丝列表里只显示文本,样式不在这应用(因为粉丝列表有自己的样式)
                // 但如果你希望粉丝列表也应用样式,可在此处处理,但鉴于需求主要是全局badge,我们保持粉丝列表只显示文本。
            }
            // ... 其余显示代码与原来相同,但为了完整,我们仍保留原有逻辑(不改动粉丝列表样式)
            let ccf_hook = '', xcpc_hook = '';
            if (user.ccfLevel) {
                const ccol = user.ccfLevel >= 8 ? "gold" : (user.ccfLevel >= 6 ? "blue" : "green");
                ccf_hook = `<svg class="svg-inline--fa fa-badge-check" viewBox="0 0 512 512" style="--fa-primary-color: #fff; --fa-secondary-color: var(--lfe-color--${ccol}-3); --fa-secondary-opacity: 1;"><g class="fa-duotone-group"><path class="fa-secondary" fill="currentColor" d="M0 256C0 292.8 20.7 324.8 51.1 340.9 41 373.8 49 411 75 437s63.3 34 96.1 23.9C187.2 491.3 219.2 512 256 512s68.8-20.7 84.9-51.1C373.8 471 411 463 437 437s34-63.3 23.9-96.1C491.3 324.8 512 292.8 512 256s-20.7-68.8-51.1-84.9C471 138.2 463 101 437 75s-63.3-34-96.1-23.9C324.8 20.7 292.8 0 256 0s-68.8 20.7-84.9 51.1C138.2 41 101 49 75 75s-34 63.3-23.9 96.1C20.7 187.2 0 219.2 0 256zm152.3 41.6c-9.2-9.5-9-24.7 .6-33.9 9.5-9.2 24.7-8.9 33.9 .6l35.8 37 106.1-145.8c7.8-10.7 22.8-13.1 33.5-5.3 10.7 7.8 13.1 22.8 5.3 33.5L244.7 352.7c-4.2 5.7-10.7 9.4-17.8 9.8-7.1 .5-14-2.2-18.9-7.3l-55.7-57.6z"></path><path class="fa-primary" fill="currentColor" d="M328.7 155.5c7.8-10.7 22.8-13.1 33.5-5.3 10.7 7.8 13.1 22.8 5.3 33.5L244.7 352.7c-4.2 5.7-10.7 9.4-17.8 9.8-7.1 .5-14-2.2-18.9-7.3l-55.7-57.6c-9.2-9.5-9-24.7 .6-33.9 9.5-9.2 24.7-8.9 33.9 .6l35.8 37 106.1-145.8z"></path></g></svg>`;
            }
            if (user.xcpcLevel) {
                const xcol = user.xcpcLevel >= 8 ? "gold" : (user.xcpcLevel >= 6 ? "blue" : "green");
                xcpc_hook = `<svg class="svg-inline--fa fa-badge-check" viewBox="0 0 512 512" style="--fa-primary-color: #fff; --fa-secondary-color: var(--lfe-color--${xcol}-3); --fa-secondary-opacity: 1;"><g class="fa-duotone-group"><path class="fa-secondary" fill="currentColor" d="M0 192C0 86 86 0 192 0S384 86 384 192c0 128-160 240-160 240l27.9 41.8c2.7 4 4.1 8.8 4.1 13.6 0 13.6-11 24.6-24.6 24.6l-78.9 0c-13.6 0-24.6-11-24.6-24.6 0-4.8 1.4-9.6 4.1-13.6L160 432S0 320 0 192zm104-16c0-39.8 32.2-72 72-72 13.3 0 24-10.7 24-24s-10.7-24-24-24c-66.3 0-120 53.7-120 120 0 13.3 10.7 24 24 24s24-10.7 24-24z"></path><path class="fa-primary" fill="currentColor" d="M56 176c0 13.3 10.7 24 24 24s24-10.7 24-24c0-39.8 32.2-72 72-72 13.3 0 24-10.7 24-24s-10.7-24-24-24C109.7 56 56 109.7 56 176z"></path></g></svg>`;
            }

            const item = insert_el(container, "div", "", "", "fcker-user");
            let info_html = `
                <img src="https://cdn.luogu.com.cn/upload/usericon/${user.uid}.png" class="left" />
                <div class="right">
                    <div class="user-title">
                        <a href="/user/${user.uid}" target="_blank" style="font-weight: bold; font-size: 1em; color: ${get_color(user.color)}">${esc_html(user.name)}</a>
                        ${ccf_hook} ${xcpc_hook}
                        ${user.badge ? `<span class="am-badge am-radius" style="font-weight: normal; background-color: ${get_color(user.color)}">${esc_html(user.badge)}</span>` : ''}
                    </div>
                    <div class="slogan">${esc_html(user.slogan || "这个家伙很懒,什么也没有留下")}</div>
                </div>
            `;
            insert_el(item, "div", info_html, "", "fcker-user-info");
            if (action_type === "unfollow") {
                const btn = insert_el(item, "button", "回敬", "", "fcker-action-btn");
                btn.style.backgroundColor = "#ff4d4f";
                btn.addEventListener("click", async () => {
                    btn.disabled = true;
                    btn.innerText = "...";
                    btn.style.backgroundColor = "#bfbfbf";
                    if (await update_relation(user.uid, 0)) btn.innerText = "已取关";
                    else { btn.disabled = false; btn.innerText = "失败或未关注"; }
                });
            } else if (action_type === "new") {
                const btn = insert_el(item, "button", "回关", "", "fcker-action-btn");
                btn.style.backgroundColor = "#52c41a";
                btn.addEventListener("click", async () => {
                    btn.disabled = true;
                    btn.innerText = "...";
                    btn.style.backgroundColor = "#bfbfbf";
                    if (await update_relation(user.uid, 1)) btn.innerText = "已互关";
                    else { btn.disabled = false; btn.innerText = "失败或已关注"; }
                });
            }
        }
    }

    get_btn.addEventListener("click", async () => {
        main.style.display = "none";
        document.body.style.overflow = "hidden";
        const mask = insert_el(fcker, "div", "", "", "fcker-modal-mask");
        const dialog = insert_el(mask, "div", "", "", "fcker-modal-dialog");
        const header = insert_el(dialog, "div", "粉丝列表", "", "fcker-modal-header");
        const quit_btn = insert_el(header, "button", "×", "", "fcker-modal-close");
        quit_btn.style.visibility = "hidden";
        function destroy_modal() {
            mask.remove();
            document.body.style.overflow = "";
            main.style.display = "";
        }
        quit_btn.addEventListener("click", destroy_modal);

        const get_card = insert_el(dialog, "div", "", "", "fcker-modal-body");
        const status_p = insert_el(get_card, "p", "", "", "");

        const now = new Date();
        let list = await get_all_followers(UID, (msg) => { status_p.innerText = msg; });
        if (list) {
            localStorage.setItem("fcker-last", now.toDateString());
            localStorage.setItem("fcker-today", JSON.stringify(list));
        }
        await refreshBadges();

        quit_btn.style.visibility = "";

        function show_followers(list) {
            get_card.innerHTML = "";
            const comp_btn = insert_el(get_card, "button", "对比差异", "", "fcker-btn");
            const save_btn = insert_el(get_card, "button", "覆盖旧列表", "", "fcker-btn");
            comp_btn.addEventListener("click", () => {
                const old_raw = localStorage.getItem("fcker");
                if (!old_raw) { alert("还没有旧列表,请先保存喵"); return; }
                const old_list = JSON.parse(old_raw);
                const old_map = new Map(old_list.map(u => [u.uid, u]));
                const now_map = new Map(list.map(u => [u.uid, u]));
                const unfollowed = [], new_followers = [];
                for (const [uid, user] of old_map.entries()) if (!now_map.has(uid)) unfollowed.push(user);
                for (const [uid, user] of now_map.entries()) if (!old_map.has(uid)) new_followers.push(user);
                get_card.innerHTML = "";
                const save_btn2 = insert_el(get_card, "button", "覆盖旧列表", "", "fcker-btn");
                save_btn2.addEventListener("click", () => {
                    localStorage.setItem("fcker", JSON.stringify(list));
                    alert("覆盖完成");
                });
                insert_el(get_card, "h4", "取关用户", "", "");
                if (unfollowed.length === 0) insert_el(get_card, "p", "无", "", "");
                else display_followers(get_card, unfollowed, "unfollow");
                insert_el(get_card, "h4", "新粉丝", "", "");
                if (new_followers.length === 0) insert_el(get_card, "p", "无", "", "");
                else display_followers(get_card, new_followers, "new");
            });
            save_btn.addEventListener("click", () => {
                localStorage.setItem("fcker", JSON.stringify(list));
                alert("覆盖完成");
            });
            display_followers(get_card, list);
        }

        if (list) show_followers(list);
    });

    // 获取 Badge 配置 Map(包含样式)
    function getBadgeMap() {
        try {
            const raw = localStorage.getItem("fcker-badge");
            if (raw) {
                // 注意:存储时使用的是 map_to_string,但 map_to_string 将对象转为JSON,因此解析后得到的是普通对象,需要再转为 Map
                const obj = JSON.parse(raw);
                const map = new Map();
                for (const [key, value] of Object.entries(obj)) {
                    // value 可能是字符串(旧格式)或对象(新格式)
                    if (typeof value === 'string') {
                        map.set(key, { text: value, style: '' });
                    } else if (typeof value === 'object' && value !== null) {
                        map.set(key, {
                            text: String(value.text || ''),
                            style: String(value.style || '')
                        });
                    }
                }
                return map;
            }
        } catch {}
        return new Map();
    }

    function injectBadgeToElement(link) {
        if (!link || link.dataset.fckerBadgeInjected === "true") return;
        const href = link.getAttribute('href');
        if (!href) return;
        const match = href.match(/^\/user\/(\d+)/);
        if (!match) return;
        const uid = match[1];
        const badges = getBadgeMap();
        if (!badges.has(uid)) return;

        // 检查是否已存在 badge(跳过文本节点)
        let next = link.nextSibling;
        while (next && next.nodeType === 3) next = next.nextSibling;
        if (next && next.classList && next.classList.contains('fcker-global-badge')) return;

        const config = badges.get(uid);
        const span = document.createElement('span');
        span.className = 'fcker-global-badge';
        span.textContent = config.text;
        // 应用自定义样式
        if (config.style) {
            span.style.cssText = config.style;
        } else {
            // 默认样式
            span.style.backgroundColor = '#888';
            span.style.color = '#fff';
            span.style.border = 'none';
        }
        link.after(span);
        link.dataset.fckerBadgeInjected = "true";
    }

    function scanAndInject() {
        const links = document.querySelectorAll('a[href^="/user/"]');
        for (const link of links) {
            injectBadgeToElement(link);
        }
    }

    function startGlobalBadgeObserver() {
        scanAndInject();
        const observer = new MutationObserver(mutations => {
            for (const mutation of mutations) {
                if (mutation.addedNodes.length) {
                    for (const node of mutation.addedNodes) {
                        if (node.nodeType === Node.ELEMENT_NODE) {
                            const links = node.querySelectorAll ? node.querySelectorAll('a[href^="/user/"]') : [];
                            for (const link of links) {
                                injectBadgeToElement(link);
                            }
                            if (node.matches && node.matches('a[href^="/user/"]')) {
                                injectBadgeToElement(node);
                            }
                        }
                    }
                }
            }
        });
        observer.observe(document.body, {
            childList: true,
            subtree: true,
        });
    }

    // 刷新 Badge(从云端获取并更新页面)
    async function refreshBadges() {
        const newBadges = await get_badges();
        if (newBadges && newBadges.size > 0) {
            // 存储为普通对象(保留结构)
            const obj = Object.fromEntries(newBadges);
            localStorage.setItem("fcker-badge", JSON.stringify(obj));
        } else {
            // 若获取失败,尝试使用已有缓存
            const cached = localStorage.getItem("fcker-badge");
            if (!cached) return;
        }
        // 清除所有注入标记,重新扫描注入
        document.querySelectorAll('a[href^="/user/"]').forEach(el => delete el.dataset.fckerBadgeInjected);
        scanAndInject();
    }

    // 初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            startGlobalBadgeObserver();
            refreshBadges();
        });
    } else {
        startGlobalBadgeObserver();
        refreshBadges();
    }

    // 定时刷新(每5分钟)
    setInterval(refreshBadges, BADGE_REFRESH_INTERVAL);

    window.addEventListener('storage', (e) => {
        if (e.key === 'fcker-badge') {
            document.querySelectorAll('a[href^="/user/"]').forEach(el => delete el.dataset.fckerBadgeInjected);
            scanAndInject();
        }
    });
}

使用方法

进入洛谷,打开任意一个新 UI 页面(比如个人主页),就可以使用啦。

你的页面右上角会多一张收起来的卡片,碰一下就会弹出来。点击上面的 「获取粉丝列表」,就可以获取当前粉丝列表。

点击后你的整个页面应该变成了一个巨丑的正在 loading… 的粉丝列表面板。别急,过一会就会显示你当前的完整粉丝列表了。

加载完成后,会显示两个按钮:

  • 「对比」,它的作用是比较当前粉丝列表和本地储存中上次储存的粉丝列表的差异。注意需要上次储存过粉丝列表才能使用。
  • 「覆盖旧列表」,它的作用是用当前粉丝列表覆盖本地储存中上次储存的粉丝列表。

原理解析

本脚本含有大量异步处理,故可以作为 js 异步使用的学习与练习。

祝所有人的粉丝只增不减!

原文