学术模式pro max ultra super

· · 科技·工程

使用Deepseek完成。有挺多bug的但是能用。

驱动:tampermonkey

这里不做过多的介绍,上手即用,自行探索吧。

代码:

// ==UserScript==
// @name         网址屏蔽器 + 专注时间
// @namespace    http://tampermonkey.net/
// @version      2.0
// @description  屏蔽包含特定字符串的网址(每个网址独立密码),带白名单和专注时间功能
// @author       You
// @match        *://*/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_listValues
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';

    // ----- 常量 -----
    const STORAGE_KEYS = {
        BLOCKED: 'blocked_urls_v2',       // [{url, password}]
        WHITELIST: 'whitelist_urls_v2',   // [string]
        FOCUS_PASSWORD: 'focus_password',
        FOCUS_END: 'focus_end_time',
        FOCUS_DURATION: 'focus_duration',
        FOCUS_ACTIVE: 'focus_active',
        FOCUS_LAST_TOTAL: 'focus_last_total', // 上次专注总时长(毫秒)
        LAST_PASSWORD: 'last_password',
    };

    const DEFAULT_PASSWORD = '123456';
    const MIN_FOCUS_MS = 5 * 60 * 1000;
    const MAX_FOCUS_MS = 6 * 60 * 60 * 1000;
    const LOCK_DURATION = 10 * 60 * 1000; // 10分钟

    const getVal = (key, def) => GM_getValue(key, def);
    const setVal = (key, val) => GM_setValue(key, val);

    // ----- 状态 -----
    let state = {
        blocked: [],        // [{url, password}]
        whitelist: [],      // [string]
        focusPassword: DEFAULT_PASSWORD,
        focusEnd: 0,
        focusDuration: 0,
        focusActive: false,
        focusLastTotal: 0,
        lastPassword: DEFAULT_PASSWORD,
    };

    // 每个被屏蔽网址的运行期锁定状态(不持久化,刷新后重置)
    // { url: { attemptsLeft, lockUntil } }
    let runtimeLock = {};

    function loadState() {
        let blockedRaw = getVal(STORAGE_KEYS.BLOCKED, null);
        // 迁移:旧版是字符串数组
        if (blockedRaw === null) {
            const old = getVal('blocked_urls', null);
            if (Array.isArray(old)) {
                blockedRaw = old.map(u => ({ url: u, password: DEFAULT_PASSWORD }));
            } else {
                blockedRaw = [];
            }
        }
        // 确保结构正确
        if (!Array.isArray(blockedRaw)) blockedRaw = [];
        blockedRaw = blockedRaw.filter(item => item && typeof item.url === 'string')
                               .map(item => ({ url: item.url, password: item.password || DEFAULT_PASSWORD }));
        state.blocked = blockedRaw;
        setVal(STORAGE_KEYS.BLOCKED, blockedRaw);

        let wl = getVal(STORAGE_KEYS.WHITELIST, null);
        if (wl === null) {
            const old = getVal('whitelist_urls', null);
            wl = Array.isArray(old) ? old : [];
        }
        state.whitelist = Array.isArray(wl) ? wl.filter(x => typeof x === 'string') : [];
        setVal(STORAGE_KEYS.WHITELIST, state.whitelist);

        state.focusPassword = getVal(STORAGE_KEYS.FOCUS_PASSWORD, DEFAULT_PASSWORD);
        state.focusEnd = getVal(STORAGE_KEYS.FOCUS_END, 0);
        state.focusDuration = getVal(STORAGE_KEYS.FOCUS_DURATION, 0);
        state.focusActive = getVal(STORAGE_KEYS.FOCUS_ACTIVE, false);
        state.focusLastTotal = getVal(STORAGE_KEYS.FOCUS_LAST_TOTAL, 0);
        state.lastPassword = getVal(STORAGE_KEYS.LAST_PASSWORD, DEFAULT_PASSWORD);

        // 自动解除过期专注
        if (state.focusActive && Date.now() > state.focusEnd) {
            autoEndFocus();
        }
    }

    function saveState() {
        setVal(STORAGE_KEYS.BLOCKED, state.blocked);
        setVal(STORAGE_KEYS.WHITELIST, state.whitelist);
        setVal(STORAGE_KEYS.FOCUS_PASSWORD, state.focusPassword);
        setVal(STORAGE_KEYS.FOCUS_END, state.focusEnd);
        setVal(STORAGE_KEYS.FOCUS_DURATION, state.focusDuration);
        setVal(STORAGE_KEYS.FOCUS_ACTIVE, state.focusActive);
        setVal(STORAGE_KEYS.FOCUS_LAST_TOTAL, state.focusLastTotal);
        setVal(STORAGE_KEYS.LAST_PASSWORD, state.lastPassword);
    }

    // 专注自然到期(非密码结束)
    function autoEndFocus() {
        state.focusActive = false;
        state.focusLastTotal = state.focusDuration;
        state.focusEnd = 0;
        saveState();
        removeBlockedOverlay();
    }

    // ----- 粒子背景 -----
    let particleCanvas = null;
    let particleAnimId = null;

    function createParticlesOverlay() {
        removeParticlesOverlay();
        const canvas = document.createElement('canvas');
        canvas.id = 'blocker-particles-canvas';
        Object.assign(canvas.style, {
            position: 'fixed',
            top: '0', left: '0',
            width: '100%', height: '100%',
            zIndex: '9999998',
            pointerEvents: 'none',
            backgroundColor: '#000000',
        });
        document.body.appendChild(canvas);
        particleCanvas = canvas;

        const ctx = canvas.getContext('2d');
        let width = canvas.width = window.innerWidth;
        let height = canvas.height = window.innerHeight;

        const onResize = () => {
            width = canvas.width = window.innerWidth;
            height = canvas.height = window.innerHeight;
        };
        window.addEventListener('resize', onResize);

        const particles = [];
        const COUNT = 80;
        class Particle {
            constructor() { this.reset(); }
            reset() {
                this.x = Math.random() * width;
                this.y = Math.random() * height;
                this.size = Math.random() * 8 + 4;
                this.speedX = Math.min(2.5, (Math.random() * 1.5 + 0.5) * (this.size / 8));
                this.speedY = (Math.random() - 0.5) * 0.6;
                this.opacity = Math.random() * 0.5 + 0.3;
            }
            update() {
                this.x += this.speedX;
                this.y += this.speedY;
                if (this.x > width + 20) { this.x = -20; this.y = Math.random() * height; }
                if (this.y > height + 20) this.y = -20;
                if (this.y < -20) this.y = height + 20;
            }
            draw() {
                ctx.fillStyle = `rgba(255,255,255,${this.opacity})`;
                ctx.fillRect(this.x, this.y, this.size, this.size);
            }
        }
        for (let i = 0; i < COUNT; i++) particles.push(new Particle());

        function animate() {
            if (!particleCanvas || !document.getElementById('blocker-particles-canvas')) return;
            ctx.fillStyle = '#000000';
            ctx.fillRect(0, 0, width, height);
            particles.forEach(p => { p.update(); p.draw(); });
            particleAnimId = requestAnimationFrame(animate);
        }
        animate();
    }

    function removeParticlesOverlay() {
        if (particleAnimId) { cancelAnimationFrame(particleAnimId); particleAnimId = null; }
        const c = document.getElementById('blocker-particles-canvas');
        if (c) c.remove();
        particleCanvas = null;
    }

    function removeBlockedOverlay() {
        const o = document.getElementById('blocker-blocked-overlay');
        if (o) o.remove();
        removeParticlesOverlay();
    }

    // ----- 屏蔽页面 -----
    // reason: 'block'(普通屏蔽,需对应网址密码) 或 'focus'(专注,需专注密码)
    // targetUrl: 普通屏蔽时对应哪条黑名单(用于取其密码)
    function showBlockedPage(reason, targetUrl) {
        removeBlockedOverlay();

        const overlay = document.createElement('div');
        overlay.id = 'blocker-blocked-overlay';
        Object.assign(overlay.style, {
            position: 'fixed', top: '0', left: '0',
            width: '100%', height: '100%',
            zIndex: '9999999',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'system-ui, sans-serif',
        });

        createParticlesOverlay();

        const box = document.createElement('div');
        Object.assign(box.style, {
            position: 'relative', zIndex: '10000000',
            backgroundColor: 'rgba(20,20,20,0.95)',
            color: '#fff', padding: '30px 40px',
            borderRadius: '12px', border: '2px solid #fff',
            textAlign: 'center', maxWidth: '500px', width: '90%',
            boxShadow: '0 0 30px rgba(255,255,255,0.2)',
        });

        const title = document.createElement('div');
        title.textContent = '此页面已被屏蔽';
        title.style.cssText = 'font-size:24px;font-weight:bold;margin-bottom:10px;';

        const subtitle = document.createElement('div');
        subtitle.textContent = reason === 'focus' ? '若要结束专注时间' : '若要浏览';
        subtitle.style.cssText = 'font-size:16px;margin-bottom:8px;color:#ddd;';

        const attemptInfo = document.createElement('div');
        attemptInfo.style.cssText = 'color:#ff6666;font-size:14px;margin-bottom:15px;';

        const input = document.createElement('input');
        input.type = 'password';
        input.placeholder = '输入密码';
        Object.assign(input.style, {
            width: '100%', padding: '10px', fontSize: '16px',
            borderRadius: '6px', border: '1px solid #aaa',
            backgroundColor: '#333', color: '#fff',
            boxSizing: 'border-box', marginBottom: '15px',
        });

        const submitBtn = document.createElement('button');
        submitBtn.textContent = '确定';
        Object.assign(submitBtn.style, {
            padding: '8px 30px', fontSize: '16px',
            borderRadius: '6px', border: 'none',
            backgroundColor: '#4CAF50', color: '#fff',
            cursor: 'pointer', fontWeight: 'bold',
        });

        box.append(title, subtitle, attemptInfo, input, submitBtn);
        overlay.appendChild(box);
        document.body.appendChild(overlay);

        // 运行期锁定状态:以 targetUrl 为键
        const lockKey = reason === 'focus' ? '__focus__' : targetUrl;
        if (!runtimeLock[lockKey]) {
            runtimeLock[lockKey] = { attemptsLeft: 3, lockUntil: 0 };
        }
        const rl = runtimeLock[lockKey];

        function updateAttemptText() {
            if (reason === 'focus') {
                attemptInfo.textContent = '输入密码结束专注时间(无限次尝试)';
                return;
            }
            if (rl.lockUntil > Date.now()) {
                const s = Math.ceil((rl.lockUntil - Date.now()) / 1000);
                attemptInfo.textContent = `已锁定,请等待 ${s} 秒(每10分钟获得1次机会)`;
            } else if (rl.attemptsLeft <= 0) {
                attemptInfo.textContent = '机会已用尽,请等待 10 分钟';
            } else {
                attemptInfo.textContent = `剩余尝试次数还有 ${rl.attemptsLeft} 次`;
            }
        }
        updateAttemptText();

        function setInputDisabled(dis) {
            input.disabled = dis;
            submitBtn.disabled = dis;
        }

        function trySubmit() {
            // 锁定检查
            if (reason !== 'focus') {
                if (rl.lockUntil > Date.now()) {
                    updateAttemptText();
                    return;
                }
                if (rl.attemptsLeft <= 0) {
                    rl.lockUntil = Date.now() + LOCK_DURATION;
                    updateAttemptText();
                    setInputDisabled(true);
                    // 10分钟后给1次机会
                    setTimeout(() => {
                        rl.lockUntil = 0;
                        rl.attemptsLeft = 1;
                        if (document.getElementById('blocker-blocked-overlay')) {
                            setInputDisabled(false);
                            updateAttemptText();
                        }
                    }, LOCK_DURATION);
                    return;
                }
            }

            const pwd = input.value;
            const correct = reason === 'focus' ? state.focusPassword
                                                : (findBlocked(targetUrl)?.password);

            if (pwd === correct) {
                removeBlockedOverlay();
                if (reason === 'focus') {
                    // 用户手动结束专注(用密码)
                    endFocusByPassword();
                }
                // 普通屏蔽:移除覆盖层即解锁
                return;
            } else {
                // 错误
                if (reason !== 'focus') {
                    rl.attemptsLeft--;
                    if (rl.attemptsLeft <= 0) {
                        rl.lockUntil = Date.now() + LOCK_DURATION;
                        setInputDisabled(true);
                        updateAttemptText();
                        setTimeout(() => {
                            rl.lockUntil = 0;
                            rl.attemptsLeft = 1;
                            if (document.getElementById('blocker-blocked-overlay')) {
                                setInputDisabled(false);
                                updateAttemptText();
                            }
                        }, LOCK_DURATION);
                    } else {
                        updateAttemptText();
                    }
                }
                input.value = '';
                input.focus();
            }
        }

        submitBtn.addEventListener('click', trySubmit);
        input.addEventListener('keydown', e => { if (e.key === 'Enter') trySubmit(); });
        input.focus();

        // 定时刷新锁定倒计时文本
        const tick = setInterval(() => {
            if (!document.getElementById('blocker-blocked-overlay')) {
                clearInterval(tick);
                return;
            }
            updateAttemptText();
        }, 500);
    }

    function findBlocked(url) {
        return state.blocked.find(b => url.includes(b.url));
    }

    // ----- 专注结束(用密码主动结束)-----
    function endFocusByPassword() {
        if (!state.focusActive) return;
        state.focusActive = false;
        state.focusLastTotal = state.focusDuration;
        state.focusEnd = 0;
        saveState();
        removeBlockedOverlay();
        renderPanelContent();
    }

    // ----- 是否应屏蔽 -----
    function shouldBlockUrl(url) {
        if (url.startsWith('chrome-extension://')) return { block: false };

        // 专注模式
        if (state.focusActive && Date.now() < state.focusEnd) {
            for (const w of state.whitelist) {
                if (url.includes(w)) return { block: false };
            }
            return { block: true, reason: 'focus' };
        }

        // 普通屏蔽
        const found = findBlocked(url);
        if (found) return { block: true, reason: 'block', target: found.url };
        return { block: false };
    }

    function interceptPage() {
        loadState();
        const url = window.location.href;
        const r = shouldBlockUrl(url);
        if (!r.block) return;

        const doShow = () => showBlockedPage(r.reason, r.target);
        if (document.body) doShow();
        else {
            const ob = new MutationObserver(() => {
                if (document.body) { ob.disconnect(); doShow(); }
            });
            ob.observe(document.documentElement, { childList: true, subtree: true });
        }
    }

    // ----- 浮动按钮 & 面板 -----
    let panel = null;
    let panelVisible = false;
    let floatingBtn = null;
    let activeTab = 'blocked';

    function createFloatingButton() {
        if (floatingBtn) return;
        floatingBtn = document.createElement('div');
        floatingBtn.id = 'blocker-floating-btn';
        floatingBtn.textContent = '🛡️';
        Object.assign(floatingBtn.style, {
            position: 'fixed', bottom: '20px', right: '20px',
            width: '50px', height: '50px', borderRadius: '50%',
            backgroundColor: '#333', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: '24px', cursor: 'pointer', zIndex: '10000001',
            boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
            userSelect: 'none', border: '2px solid #fff',
        });
        floatingBtn.addEventListener('click', e => { e.stopPropagation(); togglePanel(); });
        document.body.appendChild(floatingBtn);
    }

    function togglePanel() {
        if (panelVisible) {
            panel.style.display = 'none';
            panelVisible = false;
            return;
        }
        if (!panel) createPanel();
        else { panel.style.display = 'flex'; renderPanelContent(); }
        panelVisible = true;
    }

    function createPanel() {
        panel = document.createElement('div');
        panel.id = 'blocker-panel';
        Object.assign(panel.style, {
            position: 'fixed', bottom: '80px', right: '20px',
            width: '420px', maxHeight: '620px',
            backgroundColor: '#1e1e1e', color: '#fff',
            borderRadius: '12px', border: '1px solid #555',
            zIndex: '10000000', display: 'flex', flexDirection: 'column',
            boxShadow: '0 8px 30px rgba(0,0,0,0.6)',
            fontFamily: 'system-ui, sans-serif', fontSize: '14px',
            overflow: 'hidden',
        });

        const nav = document.createElement('div');
        nav.style.cssText = 'display:flex;border-bottom:1px solid #444;background:#2a2a2a;';

        const navBlocked = document.createElement('div');
        navBlocked.textContent = '屏蔽名单';
        navBlocked.style.cssText = 'flex:1;padding:12px;text-align:center;cursor:pointer;font-weight:bold;border-bottom:2px solid #4CAF50;';

        const navWhitelist = document.createElement('div');
        navWhitelist.textContent = '白名单 / 专注';
        navWhitelist.style.cssText = 'flex:1;padding:12px;text-align:center;cursor:pointer;color:#aaa;';

        nav.append(navBlocked, navWhitelist);
        panel.appendChild(nav);

        const content = document.createElement('div');
        content.id = 'blocker-panel-content';
        content.style.cssText = 'flex:1;overflow-y:auto;padding:12px;';
        panel.appendChild(content);

        function switchTab(tab) {
            activeTab = tab;
            if (tab === 'blocked') {
                navBlocked.style.cssText = 'flex:1;padding:12px;text-align:center;cursor:pointer;font-weight:bold;border-bottom:2px solid #4CAF50;color:#fff;';
                navWhitelist.style.cssText = 'flex:1;padding:12px;text-align:center;cursor:pointer;color:#aaa;';
            } else {
                navWhitelist.style.cssText = 'flex:1;padding:12px;text-align:center;cursor:pointer;font-weight:bold;border-bottom:2px solid #4CAF50;color:#fff;';
                navBlocked.style.cssText = 'flex:1;padding:12px;text-align:center;cursor:pointer;color:#aaa;';
            }
            renderPanelContent();
        }
        navBlocked.addEventListener('click', () => switchTab('blocked'));
        navWhitelist.addEventListener('click', () => switchTab('whitelist'));

        document.body.appendChild(panel);
        renderPanelContent();
    }

    function renderPanelContent() {
        const content = document.getElementById('blocker-panel-content');
        if (!content) return;
        content.innerHTML = '';
        if (activeTab === 'blocked') renderBlockedTab(content);
        else renderWhitelistTab(content);
    }

    function renderBlockedTab(container) {
        const addBtn = document.createElement('button');
        addBtn.textContent = '添加屏蔽网址';
        addBtn.style.cssText = 'width:100%;padding:10px;margin-bottom:12px;background:#4CAF50;color:#fff;border:none;border-radius:6px;cursor:pointer;font-weight:bold;';
        addBtn.addEventListener('click', () => showAddBlockedDialog());
        container.appendChild(addBtn);

        if (state.blocked.length === 0) {
            const empty = document.createElement('div');
            empty.textContent = '暂无屏蔽网址';
            empty.style.cssText = 'color:#888;text-align:center;padding:20px;';
            container.appendChild(empty);
            return;
        }
        state.blocked.forEach((item, index) => {
            const row = document.createElement('div');
            row.style.cssText = 'display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid #333;';
            const span = document.createElement('span');
            span.textContent = item.url;
            span.style.cssText = 'word-break:break-all;flex:1;margin-right:10px;';
            const del = document.createElement('span');
            del.textContent = '✕';
            del.style.cssText = 'color:#ff6666;cursor:pointer;font-weight:bold;font-size:18px;padding:0 5px;';
            del.addEventListener('click', () => showDeleteBlockedDialog(index));
            row.append(span, del);
            container.appendChild(row);
        });
    }

    function renderWhitelistTab(container) {
        // 专注区块
        const focus = document.createElement('div');
        focus.style.cssText = 'margin-bottom:20px;padding:12px;background:#2a2a2a;border-radius:8px;';

        const ft = document.createElement('div');
        ft.textContent = '专注时间';
        ft.style.cssText = 'font-weight:bold;margin-bottom:8px;';
        focus.appendChild(ft);

        const active = state.focusActive && Date.now() < state.focusEnd;

        if (active) {
            const timerDisplay = document.createElement('div');
            timerDisplay.style.cssText = 'font-size:16px;margin-bottom:8px;color:#4CAF50;';
            focus.appendChild(timerDisplay);

            const updateTimer = () => {
                const rem = Math.max(0, state.focusEnd - Date.now());
                const h = Math.floor(rem / 3600000);
                const m = Math.floor((rem % 3600000) / 60000);
                const s = Math.floor((rem % 60000) / 1000);
                timerDisplay.textContent = `剩余时间:${h}小时 ${m}分 ${s}秒`;
            };
            updateTimer();
            const timerInt = setInterval(() => {
                if (!panelVisible || !state.focusActive || Date.now() > state.focusEnd) {
                    clearInterval(timerInt);
                    if (state.focusActive && Date.now() > state.focusEnd) {
                        autoEndFocus();
                        renderPanelContent();
                    }
                    return;
                }
                updateTimer();
            }, 1000);

            // 密码框(专注期间清空)
            const pwdInput = document.createElement('input');
            pwdInput.type = 'password';
            pwdInput.placeholder = '输入密码结束专注';
            pwdInput.value = '';
            pwdInput.style.cssText = 'width:100%;padding:6px;margin-bottom:6px;border-radius:4px;border:1px solid #555;background:#333;color:#fff;box-sizing:border-box;';
            const endBtn = document.createElement('button');
            endBtn.textContent = '确定';
            endBtn.style.cssText = 'padding:6px 12px;background:#f44336;color:#fff;border:none;border-radius:4px;cursor:pointer;';
            endBtn.addEventListener('click', () => {
                if (pwdInput.value === state.focusPassword) {
                    endFocusByPassword();
                    renderPanelContent();
                } else {
                    alert('密码错误');
                }
            });
            pwdInput.addEventListener('keydown', e => {
                if (e.key === 'Enter') endBtn.click();
            });
            focus.append(pwdInput, endBtn);

            // 续时
            const extWrap = document.createElement('div');
            extWrap.style.cssText = 'margin-top:12px;';
            const extLabel = document.createElement('div');
            extLabel.textContent = '续时(小时:分钟)';
            extLabel.style.cssText = 'font-size:12px;margin-bottom:4px;';
            extWrap.appendChild(extLabel);

            const extRow = document.createElement('div');
            extRow.style.cssText = 'display:flex;gap:6px;align-items:center;';
            const eh = document.createElement('input');
            eh.type = 'number'; eh.placeholder = '时'; eh.min = '0'; eh.max = '6';
            eh.style.cssText = 'width:60px;padding:4px;border-radius:4px;border:1px solid #555;background:#333;color:#fff;';
            const em = document.createElement('input');
            em.type = 'number'; em.placeholder = '分'; em.min = '0'; em.max = '59';
            em.style.cssText = 'width:60px;padding:4px;border-radius:4px;border:1px solid #555;background:#333;color:#fff;';
            const extBtn = document.createElement('button');
            extBtn.textContent = '续时';
            extBtn.style.cssText = 'padding:4px 12px;background:#2196F3;color:#fff;border:none;border-radius:4px;cursor:pointer;';
            extBtn.addEventListener('click', () => {
                const h = parseInt(eh.value) || 0;
                const m = parseInt(em.value) || 0;
                if (h === 0 && m === 0) return alert('请输入时间');
                if (h > 6 || m > 59 || (h === 6 && m > 0)) return alert('单次最长6小时');
                const addMs = (h * 3600 + m * 60) * 1000;
                const newEnd = state.focusEnd + addMs;
                if (newEnd - Date.now() > MAX_FOCUS_MS) return alert('加上后超过6小时限制');
                state.focusEnd = newEnd;
                state.focusDuration += addMs;
                setVal(STORAGE_KEYS.FOCUS_END, state.focusEnd);
                setVal(STORAGE_KEYS.FOCUS_DURATION, state.focusDuration);
                renderPanelContent();
            });
            extRow.append(eh, em, extBtn);
            extWrap.appendChild(extRow);
            focus.appendChild(extWrap);

        } else {
            // 未激活:密码、时长、开始
            const pwdInput = document.createElement('input');
            pwdInput.type = 'password';
            pwdInput.placeholder = '专注密码';
            pwdInput.value = state.focusPassword;
            pwdInput.style.cssText = 'width:100%;padding:6px;margin-bottom:6px;border-radius:4px;border:1px solid #555;background:#333;color:#fff;box-sizing:border-box;';
            focus.appendChild(pwdInput);

            const timeRow = document.createElement('div');
            timeRow.style.cssText = 'display:flex;gap:6px;margin-bottom:6px;';
            const hIn = document.createElement('input');
            hIn.type = 'number'; hIn.placeholder = '小时'; hIn.min = '0'; hIn.max = '6';
            hIn.style.cssText = 'flex:1;padding:6px;border-radius:4px;border:1px solid #555;background:#333;color:#fff;';
            const mIn = document.createElement('input');
            mIn.type = 'number'; mIn.placeholder = '分钟'; mIn.min = '0'; mIn.max = '59';
            mIn.style.cssText = 'flex:1;padding:6px;border-radius:4px;border:1px solid #555;background:#333;color:#fff;';

            // 预填上次总时长
            if (state.focusLastTotal > 0) {
                hIn.value = Math.floor(state.focusLastTotal / 3600000);
                mIn.value = Math.floor((state.focusLastTotal % 3600000) / 60000);
            }
            timeRow.append(hIn, mIn);
            focus.appendChild(timeRow);

            const startBtn = document.createElement('button');
            startBtn.textContent = '开始';
            startBtn.style.cssText = 'width:100%;padding:10px;background:#4CAF50;color:#fff;border:none;border-radius:6px;cursor:pointer;font-weight:bold;';
            startBtn.addEventListener('click', () => {
                const pwd = pwdInput.value.trim() || DEFAULT_PASSWORD;
                const h = parseInt(hIn.value) || 0;
                const m = parseInt(mIn.value) || 0;
                if (h === 0 && m === 0) return alert('请输入时间');
                if (h > 6 || m > 59 || (h === 6 && m > 0)) return alert('时间最长6小时');
                const totalMs = (h * 3600 + m * 60) * 1000;
                if (totalMs < MIN_FOCUS_MS) return alert('最短5分钟');

                state.focusPassword = pwd;
                state.lastPassword = pwd;
                state.focusActive = true;
                state.focusEnd = Date.now() + totalMs;
                state.focusDuration = totalMs;
                setVal(STORAGE_KEYS.FOCUS_PASSWORD, pwd);
                setVal(STORAGE_KEYS.LAST_PASSWORD, pwd);
                setVal(STORAGE_KEYS.FOCUS_ACTIVE, true);
                setVal(STORAGE_KEYS.FOCUS_END, state.focusEnd);
                setVal(STORAGE_KEYS.FOCUS_DURATION, state.focusDuration);
                saveState();
                renderPanelContent();
                // 立即检查当前页
                const cur = window.location.href;
                const r = shouldBlockUrl(cur);
                if (r.block) showBlockedPage(r.reason, r.target);
            });
            focus.appendChild(startBtn);
        }
        container.appendChild(focus);

        // 白名单列表
        const activeFocus = state.focusActive && Date.now() < state.focusEnd;

        const addWhiteBtn = document.createElement('button');
        addWhiteBtn.textContent = '添加白名单网址';
        addWhiteBtn.style.cssText = 'width:100%;padding:10px;margin-bottom:12px;background:#2196F3;color:#fff;border:none;border-radius:6px;cursor:pointer;font-weight:bold;';
        if (activeFocus) {
            addWhiteBtn.style.opacity = '0.5';
            addWhiteBtn.style.cursor = 'not-allowed';
        }
        addWhiteBtn.addEventListener('click', () => {
            if (state.focusActive && Date.now() < state.focusEnd) {
                alert('专注期间不能添加白名单');
                return;
            }
            showAddWhitelistDialog();
        });
        container.appendChild(addWhiteBtn);

        if (state.whitelist.length === 0) {
            const empty = document.createElement('div');
            empty.textContent = '暂无白名单网址';
            empty.style.cssText = 'color:#888;text-align:center;padding:20px;';
            container.appendChild(empty);
            return;
        }
        state.whitelist.forEach((url, index) => {
            const row = document.createElement('div');
            row.style.cssText = 'display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid #333;';
            const span = document.createElement('span');
            span.textContent = url;
            span.style.cssText = 'word-break:break-all;flex:1;margin-right:10px;';
            const del = document.createElement('span');
            del.textContent = '✕';
            del.style.cssText = 'color:#ff6666;cursor:pointer;font-weight:bold;font-size:18px;padding:0 5px;';
            del.addEventListener('click', () => {
                // 白名单删除不需要密码
                state.whitelist.splice(index, 1);
                saveState();
                renderPanelContent();
            });
            row.append(span, del);
            container.appendChild(row);
        });
    }

    // ----- 添加屏蔽网址对话框(设置该网址独立密码)-----
    function showAddBlockedDialog() {
        const modal = document.createElement('div');
        Object.assign(modal.style, {
            position: 'fixed', top: '0', left: '0', width: '100%', height: '100%',
            backgroundColor: 'rgba(0,0,0,0.6)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            zIndex: '10000002',
        });
        const box = document.createElement('div');
        Object.assign(box.style, {
            backgroundColor: '#1e1e1e', color: '#fff', padding: '20px',
            borderRadius: '10px', width: '400px', maxWidth: '90%',
            boxShadow: '0 10px 40px rgba(0,0,0,0.8)',
        });

        const title = document.createElement('div');
        title.textContent = '添加屏蔽网址';
        title.style.cssText = 'font-size:18px;font-weight:bold;margin-bottom:12px;';
        box.appendChild(title);

        const urlLabel = document.createElement('div');
        urlLabel.textContent = '网址(包含此字符串即屏蔽)';
        urlLabel.style.cssText = 'font-size:12px;margin-bottom:4px;color:#aaa;';
        box.appendChild(urlLabel);

        const urlInput = document.createElement('input');
        urlInput.type = 'text';
        urlInput.value = window.location.href;
        urlInput.style.cssText = 'width:100%;padding:8px;margin-bottom:12px;border-radius:6px;border:1px solid #555;background:#333;color:#fff;box-sizing:border-box;';
        box.appendChild(urlInput);

        const pwdLabel = document.createElement('div');
        pwdLabel.textContent = '该网址的密码(解锁和删除时使用)';
        pwdLabel.style.cssText = 'font-size:12px;margin-bottom:4px;color:#aaa;';
        box.appendChild(pwdLabel);

        const pwdInput = document.createElement('input');
        pwdInput.type = 'text';
        pwdInput.placeholder = '设置密码';
        pwdInput.style.cssText = 'width:100%;padding:8px;margin-bottom:16px;border-radius:6px;border:1px solid #555;background:#333;color:#fff;box-sizing:border-box;';
        box.appendChild(pwdInput);

        const btnRow = document.createElement('div');
        btnRow.style.cssText = 'display:flex;gap:10px;justify-content:flex-end;';

        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = '取消';
        cancelBtn.style.cssText = 'padding:8px 20px;border-radius:6px;border:1px solid #555;background:transparent;color:#fff;cursor:pointer;';
        cancelBtn.addEventListener('click', () => modal.remove());

        const okBtn = document.createElement('button');
        okBtn.textContent = '确认';
        okBtn.style.cssText = 'padding:8px 20px;border-radius:6px;border:none;background:#4CAF50;color:#fff;cursor:pointer;font-weight:bold;';
        okBtn.addEventListener('click', () => {
            const url = urlInput.value.trim();
            const pwd = pwdInput.value;
            if (!url) return alert('请输入网址');
            if (!pwd) return alert('请设置密码');
            if (state.blocked.some(b => b.url === url)) return alert('该网址已在屏蔽名单中');
            state.blocked.push({ url, password: pwd });
            saveState();
            modal.remove();
            renderPanelContent();
        });

        btnRow.append(cancelBtn, okBtn);
        box.appendChild(btnRow);
        modal.appendChild(box);
        document.body.appendChild(modal);
        urlInput.focus();
    }

    // ----- 删除屏蔽网址对话框(验证该网址密码)-----
    function showDeleteBlockedDialog(index) {
        const item = state.blocked[index];
        if (!item) return;

        const modal = document.createElement('div');
        Object.assign(modal.style, {
            position: 'fixed', top: '0', left: '0', width: '100%', height: '100%',
            backgroundColor: 'rgba(0,0,0,0.6)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            zIndex: '10000002',
        });
        const box = document.createElement('div');
        Object.assign(box.style, {
            backgroundColor: '#1e1e1e', color: '#fff', padding: '20px',
            borderRadius: '10px', width: '380px', maxWidth: '90%',
        });

        const title = document.createElement('div');
        title.textContent = '确认删除';
        title.style.cssText = 'font-size:18px;font-weight:bold;margin-bottom:12px;';
        box.appendChild(title);

        const info = document.createElement('div');
        info.textContent = item.url;
        info.style.cssText = 'font-size:12px;color:#aaa;margin-bottom:12px;word-break:break-all;';
        box.appendChild(info);

        const pwdLabel = document.createElement('div');
        pwdLabel.textContent = '请输入该网址的密码';
        pwdLabel.style.cssText = 'font-size:12px;margin-bottom:4px;color:#aaa;';
        box.appendChild(pwdLabel);

        const pwdInput = document.createElement('input');
        pwdInput.type = 'password';
        pwdInput.style.cssText = 'width:100%;padding:8px;margin-bottom:16px;border-radius:6px;border:1px solid #555;background:#333;color:#fff;box-sizing:border-box;';
        box.appendChild(pwdInput);

        const btnRow = document.createElement('div');
        btnRow.style.cssText = 'display:flex;gap:10px;justify-content:flex-end;';

        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = '取消';
        cancelBtn.style.cssText = 'padding:8px 20px;border-radius:6px;border:1px solid #555;background:transparent;color:#fff;cursor:pointer;';
        cancelBtn.addEventListener('click', () => modal.remove());

        const okBtn = document.createElement('button');
        okBtn.textContent = '删除';
        okBtn.style.cssText = 'padding:8px 20px;border-radius:6px;border:none;background:#f44336;color:#fff;cursor:pointer;font-weight:bold;';
        okBtn.addEventListener('click', () => {
            // 只有这里才提示密码错误
            if (pwdInput.value !== item.password) {
                alert('密码错误');
                return;
            }
            state.blocked.splice(index, 1);
            saveState();
            modal.remove();
            renderPanelContent();
        });
        pwdInput.addEventListener('keydown', e => { if (e.key === 'Enter') okBtn.click(); });

        btnRow.append(cancelBtn, okBtn);
        box.appendChild(btnRow);
        modal.appendChild(box);
        document.body.appendChild(modal);
        pwdInput.focus();
    }

    // ----- 添加白名单对话框(无密码)-----
    function showAddWhitelistDialog() {
        const modal = document.createElement('div');
        Object.assign(modal.style, {
            position: 'fixed', top: '0', left: '0', width: '100%', height: '100%',
            backgroundColor: 'rgba(0,0,0,0.6)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            zIndex: '10000002',
        });
        const box = document.createElement('div');
        Object.assign(box.style, {
            backgroundColor: '#1e1e1e', color: '#fff', padding: '20px',
            borderRadius: '10px', width: '400px', maxWidth: '90%',
        });

        const title = document.createElement('div');
        title.textContent = '添加白名单网址';
        title.style.cssText = 'font-size:18px;font-weight:bold;margin-bottom:12px;';
        box.appendChild(title);

        const urlLabel = document.createElement('div');
        urlLabel.textContent = '网址(包含此字符串即放行)';
        urlLabel.style.cssText = 'font-size:12px;margin-bottom:4px;color:#aaa;';
        box.appendChild(urlLabel);

        const urlInput = document.createElement('input');
        urlInput.type = 'text';
        urlInput.value = '';
        urlInput.style.cssText = 'width:100%;padding:8px;margin-bottom:16px;border-radius:6px;border:1px solid #555;background:#333;color:#fff;box-sizing:border-box;';
        box.appendChild(urlInput);

        const btnRow = document.createElement('div');
        btnRow.style.cssText = 'display:flex;gap:10px;justify-content:flex-end;';

        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = '取消';
        cancelBtn.style.cssText = 'padding:8px 20px;border-radius:6px;border:1px solid #555;background:transparent;color:#fff;cursor:pointer;';
        cancelBtn.addEventListener('click', () => modal.remove());

        const okBtn = document.createElement('button');
        okBtn.textContent = '确认';
        okBtn.style.cssText = 'padding:8px 20px;border-radius:6px;border:none;background:#4CAF50;color:#fff;cursor:pointer;font-weight:bold;';
        okBtn.addEventListener('click', () => {
            const url = urlInput.value.trim();
            if (!url) return alert('请输入网址');
            if (state.whitelist.includes(url)) return alert('该网址已在白名单中');
            state.whitelist.push(url);
            saveState();
            modal.remove();
            renderPanelContent();
        });

        btnRow.append(cancelBtn, okBtn);
        box.appendChild(btnRow);
        modal.appendChild(box);
        document.body.appendChild(modal);
        urlInput.focus();
    }

    // ----- 初始化 -----
    function init() {
        loadState();

        if (state.focusActive && Date.now() > state.focusEnd) {
            autoEndFocus();
        }

        interceptPage();

        if (document.body) createFloatingButton();
        else {
            const ob = new MutationObserver(() => {
                if (document.body) { ob.disconnect(); createFloatingButton(); }
            });
            ob.observe(document.documentElement, { childList: true, subtree: true });
        }

        // SPA URL 变化
        let lastUrl = location.href;
        new MutationObserver(() => {
            const url = location.href;
            if (url !== lastUrl) {
                lastUrl = url;
                removeBlockedOverlay();
                interceptPage();
            }
        }).observe(document, { subtree: true, childList: true });

        // 定时检查专注过期
        setInterval(() => {
            if (state.focusActive && Date.now() > state.focusEnd) {
                autoEndFocus();
                renderPanelContent();
            }
        }, 30000);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();