豆包网页版插件v7.5开源- 上下对话跳转 对话框宽度调整 含源代码

该文章已生成可运行项目,

因为2026/3/4豆包网页版有更新,所以今日发此新版本

 使用教程:

https://blog.csdn.net/WF_YL/article/details/156611609?fromshare=blogdetail&sharetype=blogdetail&sharerId=156611609&sharerefer=PC&sharesource=WF_YL&sharefrom=from_link

效果:

1.消息框变窄 2.消息框变宽

3.切换上下消息

源代码:

// ==UserScript==
// @name         豆包对话导航7.5 消息列控制(修复版)
// @namespace    http://tampermonkey.net/
// @version      2026-03-05
// @description  修复宽度读取问题,确保可以超过1000px
// @author       You
// @match        https://www.doubao.com/*
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    const SELECTORS = {
        conversationItem: '[data-testid="chat_list_thread_item"]',
        activeConversation: '[data-testid="chat_list_thread_item"][aria-current="page"]',
        messageBlock: ['.message-block-container-PggqdK', '[data-testid="message-block-container"]'],
        contentContainer: '.container-SrVXPg.chrome70-container'
    };

    const SETTINGS = {
        contentMaxWidth: {
            default: 800,
            min: 600,
            max: 2400,
            step: 200
        },
        animation: {
            scrollBehavior: 'smooth',
            clickDelay: 300,
            checkInterval: 1000,
            maxCheckTimes: 10
        },
        zIndex: 99999
    };

    // 工具函数
    function safeQuerySelector(selector) {
        if (Array.isArray(selector)) {
            for (const s of selector) {
                const el = document.querySelector(s);
                if (el) return el;
            }
            return null;
        }
        return document.querySelector(selector);
    }

    function safeQuerySelectorAll(selector) {
        if (Array.isArray(selector)) {
            for (const s of selector) {
                const els = document.querySelectorAll(s);
                if (els.length > 0) return els;
            }
            return document.querySelectorAll('body > non-existent');
        }
        return document.querySelectorAll(selector);
    }

    // 对话导航函数(无修改)
    function getActiveConversation() {
        let active = safeQuerySelector(SELECTORS.activeConversation);
        if (!active) {
            const conversations = getAllConversations();
            Array.from(conversations).forEach(conv => {
                if (conv.classList.contains('e2e-test-active') ||
                    getComputedStyle(conv).backgroundColor !== 'rgba(0, 0, 0, 0)') {
                    active = conv;
                }
            });
        }
        return active;
    }

    function getAllConversations() {
        return safeQuerySelectorAll(SELECTORS.conversationItem);
    }

    function simulateClick(el) {
        if (!el) return;
        el.scrollIntoView({ behavior: SETTINGS.animation.scrollBehavior, block: 'center' });
        const rect = el.getBoundingClientRect();
        const clientX = rect.left + rect.width / 2;
        const clientY = rect.top + rect.height / 2;
        const events = [
            new MouseEvent('mouseover', { bubbles: true, clientX, clientY }),
            new MouseEvent('mousedown', { bubbles: true, clientX, clientY, button: 0 }),
            new MouseEvent('mouseup', { bubbles: true, clientX, clientY, button: 0 }),
            new MouseEvent('click', { bubbles: true, clientX, clientY })
        ];
        events.forEach(event => el.dispatchEvent(event));
        if (typeof el.click === 'function') {
            setTimeout(() => el.click(), 50);
        }
    }

    function jumpToConversation(conversationItem) {
        if (!conversationItem) {
            console.warn('豆包导航:无效的对话项');
            return;
        }
        setTimeout(() => {
            try {
                simulateClick(conversationItem);
            } catch (e) {
                console.error('豆包导航:跳转对话失败', e);
                if (conversationItem.href) window.location.href = conversationItem.href;
            }
        }, SETTINGS.animation.clickDelay);
    }

    function jumpToPreviousConversation() {
        const active = getActiveConversation();
        const conversations = Array.from(getAllConversations());
        if (!active || !conversations.length) return;
        const index = conversations.indexOf(active);
        if (index > 0) jumpToConversation(conversations[index - 1]);
    }

    function jumpToNextConversation() {
        const active = getActiveConversation();
        const conversations = Array.from(getAllConversations());
        if (!active || !conversations.length) return;
        const index = conversations.indexOf(active);
        if (index < conversations.length - 1) jumpToConversation(conversations[index + 1]);
    }

    // 消息导航函数(无修改)
    function getAllMessages() {
        return safeQuerySelectorAll(SELECTORS.messageBlock);
    }

    function getCurrentVisibleMessage() {
        const messages = Array.from(getAllMessages());
        if (!messages.length) return null;
        const viewportCenter = window.innerHeight / 2;
        let closestMsg = null;
        let minDistance = Infinity;
        messages.forEach(msg => {
            const rect = msg.getBoundingClientRect();
            if (rect.bottom < 0 || rect.top > window.innerHeight) return;
            const distance = Math.abs((rect.top + rect.height/2) - viewportCenter);
            if (distance < minDistance) {
                minDistance = distance;
                closestMsg = msg;
            }
        });
        return closestMsg;
    }

    function jumpToPreviousMessage() {
        const messages = Array.from(getAllMessages());
        const current = getCurrentVisibleMessage();
        if (!messages.length || !current) return;
        const index = messages.indexOf(current);
        if (index > 0) {
            messages[index - 1].scrollIntoView({ behavior: SETTINGS.animation.scrollBehavior, block: 'center' });
        }
    }

    function jumpToNextMessage() {
        const messages = Array.from(getAllMessages());
        const current = getCurrentVisibleMessage();
        if (!messages.length || !current) return;
        const index = messages.indexOf(current);
        if (index < messages.length - 1) {
            messages[index + 1].scrollIntoView({ behavior: SETTINGS.animation.scrollBehavior, block: 'center' });
        }
    }

    // ==================== 核心修复:列宽控制函数 ====================
    // 用一个变量在内存中缓存当前宽度,避免反复解析样式表
    let _cachedCurrentWidth = SETTINGS.contentMaxWidth.default;

    function getCurrentContentMaxWidth() {
        console.log('=== 读取当前宽度 ===');
        console.log('从缓存读取宽度:', _cachedCurrentWidth);
        return _cachedCurrentWidth;
    }

    function setContentMaxWidth(width) {
        console.log('=== 设置宽度 ===');
        console.log('输入宽度:', width);

        const min = 600;
        const max = 2400;
        width = Math.max(min, Math.min(max, width));
        console.log('边界检查后宽度:', width);

        // 更新内存中的缓存
        _cachedCurrentWidth = width;

        let styleSheet = document.getElementById('doubao-width-style');
        if (!styleSheet) {
            styleSheet = document.createElement('style');
            styleSheet.id = 'doubao-width-style';
            document.head.insertBefore(styleSheet, document.head.firstChild);
        }

        styleSheet.textContent = `
            body .max-w-\\(--content-max-width\\) {
                max-width: ${width}px !important;
                width: 100% !important;
                flex-basis: auto !important;
            }
            ${SELECTORS.contentContainer} {
                max-width: ${width}px !important;
                width: 100% !important;
            }
        `;

        console.log('最终设置的样式:', styleSheet.textContent);
        console.log(`豆包导航:宽度已设置为 ${width}px`);
    }

    function increaseContentWidth() {
        const currentWidth = getCurrentContentMaxWidth();
        console.log('点击宽按钮:', currentWidth, '→', currentWidth + SETTINGS.contentMaxWidth.step);
        setContentMaxWidth(currentWidth + SETTINGS.contentMaxWidth.step);
    }

    function decreaseContentWidth() {
        const currentWidth = getCurrentContentMaxWidth();
        console.log('点击窄按钮:', currentWidth, '→', currentWidth - SETTINGS.contentMaxWidth.step);
        setContentMaxWidth(currentWidth - SETTINGS.contentMaxWidth.step);
    }

    // UI创建函数(无修改)
    function createNavigationUI() {
        if (document.getElementById('doubao-nav-container')) return;
        const container = document.createElement('div');
        container.id = 'doubao-nav-container';
        container.style.cssText = `
            position: fixed;
            top: 50%;
            right: 0;
            transform: translateY(-50%);
            z-index: ${SETTINGS.zIndex};
            display: flex;
            flex-direction: column;
            background: #fff;
            border-radius: 6px 0 0 6px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.15);
            width: 40px;
            transition: width 0.3s ease;
            align-items: center;
        `;

        container.addEventListener('mouseenter', () => {
            container.style.width = '120px';
        });
        container.addEventListener('mouseleave', () => {
            container.style.width = '40px';
        });

        const createButton = (text, onClick, bgColor, hoverColor) => {
            const btn = document.createElement('button');
            btn.textContent = text;
            btn.onclick = onClick;
            btn.style.cssText = `
                padding: 8px 12px;
                background-color: ${bgColor};
                color: white;
                border: none;
                border-radius: 4px 0 0 4px;
                cursor: pointer;
                font-size: 14px;
                transition: background-color 0.3s;
                width: 100%;
                text-align: center;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            `;
            btn.addEventListener('mouseenter', () => {
                btn.style.backgroundColor = hoverColor;
            });
            btn.addEventListener('mouseleave', () => {
                btn.style.backgroundColor = bgColor;
            });
            return btn;
        };

        const createSeparator = () => {
            const sep = document.createElement('div');
            sep.style.cssText = `
                height: 1px;
                background-color: rgba(0, 0, 0, 0.2);
                margin: 4px 8px;
                width: 80%;
            `;
            return sep;
        };

        container.appendChild(createButton('← 上一个对话', jumpToPreviousConversation, '#1890ff', '#40a9ff'));
        container.appendChild(createButton('→ 下一个对话', jumpToNextConversation, '#1890ff', '#40a9ff'));
        container.appendChild(createSeparator());
        container.appendChild(createButton('↑ 上一条消息', jumpToPreviousMessage, '#52c41a', '#73d13d'));
        container.appendChild(createButton('↓ 下一条消息', jumpToNextMessage, '#52c41a', '#73d13d'));
        container.appendChild(createSeparator());
        container.appendChild(createButton('宽', increaseContentWidth, '#faad14', '#ffc53d'));
        container.appendChild(createButton('窄', decreaseContentWidth, '#faad14', '#ffc53d'));

        document.body.appendChild(container);
        console.log('豆包导航:UI已创建完成');
    }

    // 初始化函数
    function initKeyboardListener() {
        document.addEventListener('keydown', (e) => {
            const activeEl = document.activeElement;
            if (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA' ||
                activeEl.isContentEditable) return;

            if (e.altKey) {
                switch(e.key) {
                    case 'ArrowLeft':
                        e.preventDefault();
                        jumpToPreviousConversation();
                        break;
                    case 'ArrowRight':
                        e.preventDefault();
                        jumpToNextConversation();
                        break;
                    case 'PageUp':
                        e.preventDefault();
                        jumpToPreviousMessage();
                        break;
                    case 'PageDown':
                        e.preventDefault();
                        jumpToNextMessage();
                        break;
                }
            }
        });
    }

    function init() {
        initKeyboardListener();
        console.log('初始化宽度:', SETTINGS.contentMaxWidth.default);
        setContentMaxWidth(SETTINGS.contentMaxWidth.default);

        if (document.readyState === 'complete') {
            createNavigationUI();
        } else {
            window.addEventListener('load', createNavigationUI);
        }

        let checkCount = 0;
        const checkInterval = setInterval(() => {
            if (!document.getElementById('doubao-nav-container')) {
                createNavigationUI();
            }
            checkCount++;
            if (checkCount >= SETTINGS.animation.maxCheckTimes) {
                clearInterval(checkInterval);
            }
        }, SETTINGS.animation.checkInterval);

        console.log('豆包对话导航脚本已初始化完成');
    }

    // 启动脚本
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值