百度全页面样式统一

添加"官网置顶"功能,优化百度官方标识识别,增加深色模式切换,移除百度搜索结果跳转页面,并加宽搜索结果

// ==UserScript==
// @name         百度全页面样式统一
// @namespace    http://tampermonkey.net/
// @version      1.23
// @icon         https://i.imgur.com/TEmC7lb.png
// @description  添加"官网置顶"功能,优化百度官方标识识别,增加深色模式切换,移除百度搜索结果跳转页面,并加宽搜索结果
// @author       Gemini
// @match        *://www.baidu.com/*
// @match        *://www1.baidu.com/*
// @match        *://m.baidu.com/*
// @match        *://xueshu.baidu.com/*
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @run-at       document-start
// @connect      *
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // ==============================================
    // 稳定可靠的防闪烁/防白屏技术
    // ==============================================
    const observer = new MutationObserver(() => {
        if (document.body) {
            document.body.style.opacity = '0';
            observer.disconnect();
        }
    });
    observer.observe(document.documentElement, { childList: true });

    // ==============================================
    // 重定向功能工具函数
    // ==============================================
    function getUrlAttribute(baseUrl = location.href, attribute, needDecode = true) {
        const [, search = ''] = baseUrl.split("?");
        const searchValue = search.split("&");
        for (let i = 0; i < searchValue.length; i++) {
            const [key, value] = searchValue[i].split("=");
            if (key === attribute) {
                return needDecode ? decodeURIComponent(value) : value;
            }
        }
        return "";
    }

    function Reg_Get(HTML, reg) {
        const RegE = new RegExp(reg);
        try {
            return RegE.exec(HTML)[1];
        } catch (e) {
            return "";
        }
    }

    // ==============================================
    // 重定向处理核心函数
    // ==============================================
    function removeMobileBaiduDirectLink() {
        const nodes = document.querySelectorAll("#page #page-bd #results .result:not([ac_redirectStatus])");
        nodes.forEach(curNode => {
            try {
                const logData = curNode.getAttribute('data-log');
                if (!logData) return;

                const curData = JSON.parse(logData.replace(/'/gm, '"'));
                const trueLink = curData.mu;

                if (trueLink) {  // 修正:将true极客时间Link改为trueLink
                    const article = curNode.querySelector("article");
                    if (article) article.setAttribute("rl-link-href", trueLink);

                    curNode.querySelectorAll("a").forEach(a => {
                        // 保留原始链接作为备用
                        a.setAttribute("data-original-href", a.href);
                        a.setAttribute("href", trueLink);
                    });
                }

                curNode.setAttribute("ac_redirectStatus", "1");
            } catch (e) {
                console.error('处理百度移动重定向失败', e);
            }
        });
    }

    function remove_xueshuBaidu() {
        if (location.host.includes('xueshu.baidu')) {
            const xnodes = document.querySelectorAll("a[href*='sc_vurl=http']");
            xnodes.forEach(node => {
                const xurl = getUrlAttribute(node.href, "sc_vurl", true);
                if (xurl) {
                    // 保留原始链接作为备用
                    node.setAttribute("data-original-href", node.href);
                    node.href = xurl;
                }
            });
        }
    }

    function resetURLNormal() {
        // 百度PC版选择器
        const mainSelector = "#content_left>.c-container";
        const linkSelector = "h3.t>a, .c-container article a";

        // 百度移动版选择器
        if (location.host.includes('m.baidu')) {
            removeMobileBaiduDirectLink();
            return;
        }

        const mainList = document.querySelectorAll(mainSelector);
        const hasDealHrefSet = new Set();

        mainList.forEach(curNode => {
            if (curNode.getAttribute("ac_redirectStatus") !== null) return;
            curNode.setAttribute("ac_redirectStatus", "0");

            const linkNode = curNode.querySelector(linkSelector);
            if (!linkNode || !linkNode.href) return;

            let linkHref = linkNode.href;
            if (hasDealHrefSet.has(linkHref)) return;
            hasDealHrefSet.add(linkHref);

            // 处理特殊链接
            if (linkHref.startsWith('javascript') || linkHref.startsWith('#')) return;

            // 检查是否可以直接处理
            let trueLink = curNode.getAttribute('mu') || linkNode.getAttribute('data-mdurl');
            if (trueLink && !trueLink.includes('nourl')) {
                // 添加百度编码处理
                if (trueLink.includes('baidu.com')) {
                    const [, first = ''] = /(ie=[^&]+)/.exec(location.search) || [];
                    trueLink = trueLink.replace(/(ie=[^&]+)/, first);
                }

                dealRedirect(null, linkHref, trueLink, linkNode);
                return;
            }

            // 需要请求接口处理的重定向
            if (linkHref.includes("www.baidu.com/link")) {
                let url = linkHref.replace(/^http:/, "https:");
                if (!url.includes("eqid")) {
                    url = url + "&wd=&eqid=";
                }

                GM_xmlhttpRequest({
                    url: url,
                    headers: {
                        "Accept": "*/*",
                        "Referer": linkHref.replace(/^http:/, "https:")
                    },
                    method: "GET",
                    timeout: 8000,
                    onload: function(response) {
                        if (response.responseText || response.responseHeaders) {
                            let resultResponseUrl = Reg_Get(response.responseText, "URL='([^']+)'");

                            // 备选方案
                            if (!resultResponseUrl && response.responseHeaders.includes("tm-finalurl")) {
                                resultResponseUrl = Reg_Get(response.responseHeaders, "tm-finalurl\\w+: ([^\\s]+)");
                            }

                            dealRedirect(this, linkHref, resultResponseUrl, linkNode);
                        }
                    }
                });
            }
        });
    }

    function dealRedirect(request, curNodeHref, resultResponseUrl, linkNode) {
        if (!resultResponseUrl || resultResponseUrl.includes("www.baidu.com/link")) return;

        try {
            // 更新链接地址
            if (linkNode) {
                // 保留原始链接作为备用
                linkNode.setAttribute("data-original-href", linkNode.href);
                linkNode.href = resultResponseUrl;

                // 更新链接文本显示域名
                if (linkNode.text && linkNode.text.length < 10 &&
                    !linkNode.parentElement.tagName.toLowerCase().startsWith("h")) {
                    const host = new URL(resultResponseUrl).hostname;
                    if (!linkNode.textContent.includes(host)) {
                        const hostSpan = document.createElement('span');
                        hostSpan.className = 'gm-host-name';
                        hostSpan.textContent = host;

                        // 添加分隔符
                        const separator = document.createElement('span');
                        separator.className = 'gm-host-separator';
                        separator.textContent = ' - ';

                        linkNode.parentNode.insertBefore(separator, linkNode.nextSibling);
                        linkNode.parentNode.insertBefore(hostSpan, separator.nextSibling);
                    }
                }
            }

            if (request) request.abort();
        } catch (e) {
            console.error('处理重定向失败', e);
        }
    }

    // 重定向处理的主函数
    function processRedirects() {
        remove_xueshuBaidu();
        resetURLNormal();
    }

    // ==============================================
    // 通用模块
    // ==============================================
    const customSearchBoxHTML =
          '<div class="gm-search-container">' +
          '<input class="gm-search-input" type="text" maxlength="255" autocomplete="off" placeholder="请输入搜索内容">' +
          '<button class="gm-search-button">百度一下</button>' +
          '</div>';

    const commonStyles =
          '.gm-search-input { width: 600px; height: 42px; padding-left: 25px; border: 1px solid #c4c7ce !important; box-sizing: border-box !important; border-right: none !important; outline: none !important; font-size: 16px; color: #000; background: #fff; border-radius: 24px 0 0 24px; }' +
          '.gm-search-input:focus { border-color: #4e6ef2 !important; }' +
          '.gm-search-button { height: 42px; padding: 0 25px; border: none !important; box-sizing: border-box !important; outline: none !important; cursor: pointer; font-size: 17px; background: #4e6ef2; border-radius: 0 24px 24px 0; color: #fff; display: flex; align-items: center; justify-content: center; white-space: nowrap; }' +
          '.gm-search-button:hover { background: #3079e8; }' +
          '.official-pinned-hint { background: #4e6ef2; color: white; padding: 3px 10px; border-radius: 4px; font-size: 12px; margin-bottom: 8px; display: inline-block; }' +

          /* 重定向优化样式 */
          '.gm-host-name { color: #666; font-size: 13px; margin-left: 4px; }' +
          '.gm-host-separator { color: #999; }' +
          'body.dark-mode .gm-host-name { color: #aaa; }' +
          'body.dark-mode .gm-host-separator { color: #777; }' +

          /* ================ 加宽效果样式 ================ */
          '/* 搜索结果容器居中 */' +
          '#container.sam_newgrid, ' +
          '#content_left, ' +
          '.wrapper_new #content_left, ' +
          '#container.sam_newgrid #content_left { ' +
          '   width: 100% !important; ' +
          '   max-width: 1200px !important; ' +
          '   margin: 0 auto !important; ' +
          '   padding: 0 !important; ' +
          '   display: flex !important; ' +
          '   flex-direction: column !important; ' +
          '   align-items: center !important; ' +
          '}' +

          '/* 搜索结果项加宽居中 */' +
          '.c-container, ' +
          '.result-op, ' +
          '.result { ' +
          '   width: 100% !important; ' +
          '   max-width: 800px !important; ' +
          '   margin: 0 auto 25px auto !important; ' +
          '   padding: 25px !important; ' +
          '   border-radius: 10px !important; ' +
          '   box-shadow: 0 3px 10px rgba(0,0,0,0.08) !important; ' +
          '   background-color: #fff !important; ' +
          '   transition: all 0.3s ease !important; ' +
          '   box-sizing: border-box !important; ' +
          '}' +

          '.c-container:hover, .result-op:hover, .result:hover { ' +
          '   box-shadow: 0 6px 15px rgba(0,0,0,0.12) !important; ' +
          '   transform: translateY(-3px) !important; ' +
          '}' +

          '/* 整体页面加宽 */' +
          '#wrapper_wrapper, #container { ' +
          '   max-width: 100% !important; ' +
          '   padding: 0 20px !important; ' +
          '   box-sizing: border-box !important; ' +
          '}' +

          '/* 屏蔽右侧信息栏 */' +
          '#content_right, #con-ar { ' +
          '   display: none !important; ' +
          '}';

    '/* 官方网站已置顶样式 */' +
        GM_addStyle(
        '.gm-official-hint {' +
        'position: absolute;' +
        'left: 5px;' +
        'bottom: 5px;' +
        'padding: 6px 12px !important;' +
        'background: #4e6ef2 !important;' +
        'color: white !important;' +
        'border-radius: 4px !important;' +
        'font-size: 13px !important;' +
        'box-shadow: 0 2px 4px rgba(0,0,0,0.2);' +
        'z-index: 1;' +
        '}' +

        '/* 为第一个搜索结果添加相对定位 */' +
        '#content_left > .c-container:first-child, ' +
        '#content_left > .result:first-child {' +
        'position: relative;' +
        'padding-bottom: 30px !important; /* 增加底部空间以容纳提示 */' +
        '}' +

        '/* 标签容器居中样式 */' +
        '.tag-wrapper_1sGop {' +
            'display: flex !important;' +
            'justify-content: center !important;' +
            'width: 100% !important;' +
            'max-width: 900px !important;' +
            'margin: 0 auto !important;' +
            'padding: 0 !important;' +
        '}' +

        '.tag-scroll_3EMBO {' +
            'display: flex !important;' +
            'flex-wrap: wrap !important;' +
            'justify-content: center !important;' +
            'gap: 5px !important;' +
            'max-width: 100% !important;' +
        '}'
    );
    // ==============================================
    // 核心执行函数
    // ==============================================
    const runModifications = () => {
        try {
            if (window.location.pathname === '/') {
                const homepageStyles =
                      '#form, #s_form, .s_btn_wr, .s_ipt_wr, .fm, .ai-input, .s-center-box, #s_main, #s_new_search_guide, #bottom_layer, #bottom_space { display: none !important; }' +
                      '#lg, #lg img { display: block !important; opacity: 1 !important; visibility: visible !important; }' +
                      '.gm-search-container { position: absolute; top: 220px; left: 50%; transform: translateX(-50%); z-index: 9999; display: flex; box-shadow: 0 2px 4px rgba(0,0,0,0.2); }';
                GM_addStyle(commonStyles + homepageStyles);
                if (!document.querySelector('.gm-search-container')) {
                    document.body.insertAdjacentHTML('beforeend', customSearchBoxHTML);
                    document.querySelector('.gm-search-input')?.focus();
                    attachEventListeners();
                }
            }
            else if (window.location.pathname === '/s') {
                const resultsPageStyles =
                      '/* 屏蔽百度推广、AI结果和聚合卡片 */' +
                      '#content_left > div[style*="display:block !important"], #content_left > div[data-ec-ad-type], .ai-entry.cos-space-mb-xs, .c-group-wrapper' +
                      '{ display: none !important; }' +

                      '#s_form, #u { display: none !important; }' +
                      '#head { height: 60px !important; display: flex; align-items: center; justify-content: center; background: #fff !important; border-bottom: 1px solid #e4e7ed !important; transition: background-color 0.3s, border-color 0.3s; }' +
                      '#container { padding-top: 10px !important; }' + // 宽度已在commonStyles中设置
                      '#s_tab { width: fit-content !important; margin-left: auto !important; margin-right: auto !important; padding-left: 0 !important; }' +
                      '#s_tab .s-tab-item { margin-left: 12px !important; margin-right: 12px !important; }' +
                      '.gm-search-container { display: flex; margin: 0 auto; justify-content: center; }' +

                      '/* 兼容并居中两种标签容器,并取消其可能存在的置顶行为 */' +
                      '.tag-container_ksKXH, .wrapper_l .tag-wrapper_1sGop { width: fit-content; margin: 0px auto !important; position: relative !important; top: unset !important; bottom: unset !important; }' +

                      '#dark-mode-toggle { position: fixed; bottom: 30px; left: 30px; width: 48px; height: 48px; background-color: #f1f3f4; border: none; border-radius: 50%; display: flex; justify-content: center; align-items: center; cursor: pointer; z-index: 10000; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); transition: all 0.3s cubic-bezier(.25,.8,.25,1) !important; overflow: hidden; }' +
                      '#dark-mode-toggle:hover { transform: scale(1.08); box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2); }' +  // 修正:删除多余的"极客时间"文本
                      '#dark-mode-toggle:active { transform: scale(0.98); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); }' +
                      '.dark-mode-icon-sun, .dark-mode-icon-moon { position: absolute; transition: all 0.4s ease-in-out; }' +  // 修正:将dark-mode-icon-s极客时间un改为dark-mode-icon-sun
                      '.dark-mode-icon-sun { width: 22px; height: 22px; border-radius: 50%; background: #F9A825; box-shadow: 0 0 8px 1px #F9A825; opacity: 1; transform: scale(1) rotate(0deg); }' +
                      '.dark-mode-icon-moon { width: 22px; height: 22px; border-radius: 50%; box-shadow: inset 8px -8px 0 0 #fff; opacity: 0; transform: scale(0.5) rotate(-90deg); }' +

                      '/* --- 深色模式核心样式 --- */' +
                      'body.dark-mode { background-color: #1a1a1a !important; color: #e8e6e3 !important; }' +
                      'body.dark-mode #head { background: #252525 !important; border-bottom: 1px solid #333 !important; }' +
                      'body.dark-mode .gm-search-input { background: #333; border-color: #555 !important; color: #e8e6e3 !important; }' +
                      'body.dark-mode .c-container, body.dark-mode .result-op, body.dark-mode .result[tpl="soft"], body.dark-mode div[class*="_aladdin"] { background-color: #252525 !important; border: 1px solid #333 !important; border-radius: 8px; padding: 15px; }' +
                      'body.dark-mode .c-container > .t.c-title, body.dark-mode .tags_2yHYj, body.dark-mode .cos-tabs.cos-tabs-bar .cos-tabs-header, body.dark-mode .tag-container_ksKXH, body.dark-mode .wrapper_l .tag-wrapper_1sGop { background-color: transparent !important; }' +
                      'body.dark-mode #content_left a, body.dark-mode #content_left h3[class*="title"], body.dark-mode #content_left h3[class*="title"] *, body.dark-mode #content_left .op-soft-title, body.dark-mode #content_left .op-soft-title *, body.dark-mode .tag-container_ksKXH a, body.dark-mode .wrapper_l .tag-wrapper_1sGop a { color: #8ab4f8 !important; text-decoration: none !important; background-color: transparent !important; text-shadow: 0 0 2px rgba(0,0,0,0.5) !important; }' +
                      'body.dark-mode #content_left a:hover { text-decoration: underline !important; }' +
                      'body.dark-mode .c-abstract, body.dark-mode .c-abstract *, body.dark-mode .c-span-last, body.dark-mode .summary-text_560AW, body.dark-mode .summary-text_560AW *, body.dark-mode #content_left em, body.dark-mode .new-pmd .c-color-text, body.dark-mode .cu-color-text { color: #e8e6e3 !important; text-shadow: 0 0 2px rgba(0,0,0,0.5) !important; }' +
                      'body.dark-mode #content_left em { font-style: italic !important; }' +
                      'body.dark-mode .op-soft-info-text, body.dark-mode .c-showurl, body.dark-mode .c-showurl *, body.dark-mode .cosc-source-text, body.dark-mode .cos-color-text-minor, body.dark-mode .op_translation_usertip { color: #999 !important; text-shadow: none !important; }' +
                      'body.dark-mode div[class*="stock-container"] * { color: #e8e6e3 !important; background: none !important; background-color: transparent !important; text-shadow: 0 0 2px rgba(0,0,0,0.5) !important; }' +
                      'body.dark-mode div[class*="stock-container"] a { color: #8ab4f8 !important; }' +
                      'body.dark-mode .op-stock-nav-item-selected { background-color: #3a3a3a !important; border-radius: 4px !important; }' +
                      'body.dark-mode #s_tab a, body.dark-mode #s_tab span { color: #ccc !important; text-decoration: none !important; text-shadow: none !important; }' +
                      'body.dark-mode #s_tab .s-tab-item.current span { color: #fff !important; }' +
                      'body.dark-mode #s_tab .s-tab-item.current { border-bottom-color: #4e6ef2 !important; }' +
                      'body.dark-mode #page a, body.dark-mode #page strong { background-color: #333 !important; border: 1px solid #555 !important; color: #e8e3e3 !important; text-shadow: none !important; }' +
                      'body.dark-mode #page strong, body.dark-mode #page a.n:hover { background-color: #4e6ef2 !important; color: #fff !important; border-color: #4e6ef2 !important; }' +
                      'body.dark-mode #dark-mode-toggle { background-color: #3c4043; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4); }' +
                      'body.dark-mode #dark-mode-toggle:hover { background-color: #4d5154; box-shadow: 0 6px 16px rgba(0, 0, 0, 0.5); }' +
                      'body.dark-mode .dark-mode-icon-sun { opacity: 0; transform: scale(0.5) rotate(90deg); }' +
                      'body.dark-mode .dark-mode-icon-moon { opacity: 1; transform: scale(1) rotate(0deg); box-shadow: inset 8px -8px 0 0 #e8eaed; }' +
                      'body.dark-mode .text-con_6ko8Y * { color: #e8e6e3 !important; text-shadow: 0 0 2px rgba(0,0,0,0.5) !important; }' +
                      'body.dark-mode .words-text_5Ps7D { color: #8ab4f8 !important; text-shadow: 0 0 2px rgba(0,0,0,0.5) !important; }' +
                      'body.dark-mode .common-text_2R17p.cos-font-medium, body.dark-mode object.cos-line-clamp-2 .mean-text_4MwRe { color: #e8e6e3 !important; text-shadow: 0 0 2px rgba(0,0,0,0.5) !important; }' +
                      'body.dark-mode .fy-dictwisenew-tip_79GW0 { color: #999 !important; text-shadow: none !important; }' +
                      'body.dark-mode .cos-search-link-text, body.dark-mode .cos-icon-research { color: #8ab4f8 !important; text-shadow: 0 0 2px rgba(0,0,0,0.5) !important; }' +
                      'body.dark-mode .words-text_5Ps7D, body.dark-mode .words-text_5Ps7D span { color: #8ab4f8 !important;text-shadow: 0 0 2px rgba(0,0,0,0.5) !important; }' +
                      'body.dark-mode .cos-color-text-tiny { color: #999 !important; text-shadow: none !important; }' +
                      'body.dark-mode .tabContainer_4bRe9 { background: transparent !important; border-bottom: 1px solid #444 !important; }' +
                      'body.dark-mode .tabItem_14YyZ span, body.dark-mode .tabItem_14YyZ .cos-icon { color: #999 !important; }' +
                      'body.dark-mode .tabItem_14YyZ.active_2sYvR span, body.dark-mode .tabItem_14YyZ.active_2sYvR .cos-icon { color: #fff !important; }' +
                      'body.dark-mode .tabItem_14YyZ.active_2sYvR { border-bottom: 2px solid #4e6ef2 !important; }' +
                      'body.dark-mode .item_uMLQg .number_7sHfk, body.dark-mode .item_uMLQg .desc_1V5he { color: #e8e6e3 !important; }' +
                      'body.dark-mode .item_uMLQg .red_e7rrn .number_7sHfk, body.dark-mode .item_uMLQg .red_e7rrn .desc_1V5he { color: #e8e6e3 !important; }' +
                      'body.dark-mode .item_uMLQg .selected_3I0vG { background-color: #3c4043 !important; border-radius: 8px; }' +
                      'body.dark-mode .item_uMLQg .selected_3I0vG .number_7sHfk, body.dark-mode .item_uMLQg .selected_3I0vG .desc_1V5he { color: #e8e6e3 !important; }' +
                      'body.dark-mode .jrStockColorCommon_5usgg { color: #e8e6e3 !important; text-shadow: 0 0 2px rgba(0,0,0,0.5) !important; }'

                ;

                GM_addStyle(commonStyles + resultsPageStyles);

                const header = document.getElementById('head');
                if (header) { header.innerHTML = customSearchBoxHTML; }
                const query = new URLSearchParams(window.location.search).get('wd');
                if (query) { document.querySelector('.gm-search-input').value = query; }

                attachEventListeners();
                rankOfficialSite();
                setupDarkModeToggle();

                // 添加重定向处理
                processRedirects();
                initRedirectObserver();
            }
        } catch (error) {
            console.error('百度样式脚本出现错误:', error);
        } finally {
            if (document.body) { document.body.style.opacity = '1'; }
        }
    };

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

    // ==============================================
    // 辅助函数
    // ==============================================
    function attachEventListeners() {
        const input = document.querySelector('.gm-search-input');
        const button = document.querySelector('.gm-search-button');
        const doSearch = () => {
            const query = input.value.trim();
            if (query) { window.location.href = 'https://www.baidu.com/s?wd=' + encodeURIComponent(query); }
        };
        if(button) button.addEventListener('click', doSearch);
        if(input) input.addEventListener('keydown', (event) => { if (event.key === 'Enter') { doSearch(); } });
    }

    function setupDarkModeToggle() {
        if(document.getElementById('dark-mode-toggle')) return;
        const toggleButton = document.createElement('div');
        toggleButton.id = 'dark-mode-toggle';
        toggleButton.innerHTML = '<span class="dark-mode-icon-sun"></span><span class="dark-mode-icon-moon"></span>';
        document.body.appendChild(toggleButton);

        const updateState = (isDark) => {
            if (isDark) {
                document.body.classList.add('dark-mode');
            } else {
                document.body.classList.remove('dark-mode');
            }
        };

        toggleButton.addEventListener('click', () => {
            const isDarkMode = !document.body.classList.contains('dark-mode');
            GM_setValue('darkMode', isDarkMode);
            updateState(isDarkMode);
        });

        const savedMode = GM_getValue('darkMode', false);
        updateState(savedMode);
    }

    function rankOfficialSite() {
        setTimeout(() => {
            const resultsContainer = document.getElementById('content_left');
            if (!resultsContainer) return;

            const results = Array.from(resultsContainer.children).filter(el => el.matches('.c-container[id], .result[id]'));
            let bestResult = null;
            let topScore = -1;
            const query = new URLSearchParams(window.location.search).get('wd') || '';

            results.forEach((result, index) => {
                let score = 0;
                const linkElement = result.querySelector('h3 a, .t a');
                if (!linkElement) return;

                const href = linkElement.href || '';
                const title = linkElement.textContent || '';

                // 官方标识检测
                const isOfficial = result.querySelector('span.suffix-icon_3Ox2w span.tag_6iNm4.www-tag-fill-blue_3n0y3') ||
                      (result.querySelector('span.tag_6iNm4') && result.querySelector('span.tag_6iNm4').textContent.trim() === '官方') ||
                      result.querySelector('[data-is-official="1"]') ||
                      result.querySelector('.c-icon-official');

                // 计分逻辑
                if (isOfficial) score += 150;
                if (index === 0) score += 50;

                try {
                    const domain = new URL(href).hostname.replace('www.', '');
                    if (query && domain.startsWith(query.toLowerCase().replace(/\s/g, ''))) score += 30;
                } catch (e) {}

                if (title.includes('官网') || title.includes('官方')) score += 20;

                if (score > topScore) {
                    topScore = score;
                    bestResult = result;
                }
            });

            // 符合条件的官方网站置顶
            if (bestResult && topScore > 100) {
                // 确保bestResult是第一个结果
                if (resultsContainer.firstElementChild !== bestResult) {
                    resultsContainer.insertBefore(bestResult, resultsContainer.firstElementChild);
                }

                // 创建或更新提示元素
                let hint = bestResult.querySelector('.gm-official-hint');
                if (!hint) {
                    hint = document.createElement('div');
                    hint.className = 'gm-official-hint';
                    bestResult.appendChild(hint);
                }

                hint.textContent = '官方网站已置顶';
                console.log('Tampermonkey: 已将识别到的官方网站置顶 ->', bestResult.querySelector('h3, .t').textContent);
            }
        }, 1200);
    }





    // ==============================================
    // 重定向监听器
    // ==============================================
    function initRedirectObserver() {
        const observer = new MutationObserver(mutations => {
            let needsUpdate = false;

            mutations.forEach(mutation => {
                if (mutation.addedNodes.length) {
                    needsUpdate = true;
                }
            });

            if (needsUpdate) {
                processRedirects();
            }
        });

        observer.observe(document, {
            childList: true,
            subtree: true,
            attributes: false,
            characterData: false
        });
    }
})();