百度重定向Google搜索

当输入以"``"或"··"开头的查询时,自动重定向到Google搜索

// ==UserScript==
// @name         百度重定向Google搜索
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  当输入以"``"或"··"开头的查询时,自动重定向到Google搜索
// @author       wze
// @match        *://www.baidu.com/*
// @grant        none
// @run-at       document-start
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';
    const prefixes = ['``', '··']; 

    function redirectIfNeeded(query) {
        if (!query) return false;
        const trimmedQuery = query.trim();
        for (const prefix of prefixes) {
            if (trimmedQuery.startsWith(prefix)) {
                const googleQuery = trimmedQuery.substring(prefix.length).trim();
                window.location.replace(`https://www.google.com/search?q=${encodeURIComponent(googleQuery)}`);
                return true;
            }
        }
        return false;
    }

    function checkUrlParams() {
        const params = new URLSearchParams(window.location.search);
        const query = params.get('wd') || params.get('word');
        return redirectIfNeeded(query);
    }

    if (checkUrlParams()) {
        return;
    }

    function getSearchInput() {
        return document.getElementById('kw') ||
               document.querySelector('input[name="wd"]') ||
               document.querySelector('input[type="search"]');
    }

    function bindSearchEvent(searchInput) {
        if (searchInput && !searchInput._redirectBound) {
            searchInput._redirectBound = true;
            const form = searchInput.form || document.querySelector('form[action="/s"]');
            if (form) {
                form.addEventListener('submit', function(e) {
                    const query = searchInput.value;
                    if (redirectIfNeeded(query)) {
                        e.preventDefault();
                    }
                });
            }
        }
    }

    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes.length) {
                const searchInput = getSearchInput();
                if (searchInput) {
                    bindSearchEvent(searchInput);
                }
            }
        });
    });

    observer.observe(document.documentElement, { childList: true, subtree: true });

    const initialSearchInput = getSearchInput();
    if (initialSearchInput) {
        bindSearchEvent(initialSearchInput);
    }
})();