Yandex Wikipedia Info

Добавляет дополнительную информацию из Wikipedia в боковую панель поиска Yandex.

当前为 2024-10-13 提交的版本,查看 最新版本

// ==UserScript==
// @name         Yandex Wikipedia Info
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  Добавляет дополнительную информацию из Wikipedia в боковую панель поиска Yandex.
// @author       zzakhar
// @match        *://yandex.ru/*
// @grant        GM_xmlhttpRequest
// @grant        GM_addElement
// @connect      ru.wikipedia.org
// @license      CC BY-NC-ND
// ==/UserScript==

(function() {
    'use strict';

    let lastQuery = '';

    function sendWikipediaRequest(query, callback) {
        const wikiUrl = `https://ru.wikipedia.org/wiki/${encodeURIComponent(query)}`;
        console.log('Отправляю запрос:', wikiUrl);

        GM_xmlhttpRequest({
            method: "GET",
            url: wikiUrl,
            onload: function(response) {
                if (response.status === 200) {
                    const doc = new DOMParser().parseFromString(response.responseText, 'text/html');
                    const infobox = doc.querySelector('#mw-content-text .infobox');
                    if (infobox) {
                        callback(null, doc);
                    } else {
                        callback('Информация не найдена');
                    }
                } else {
                    callback('Ошибка при запросе');
                }
            },
            onerror: function() {
                callback('Ошибка при запросе');
            }
        });
    }

    function processWikipediaResponse(doc) {
        const searchResultAside = document.querySelector('#search-result-aside');
        const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;

        const infoDiv = GM_addElement(searchResultAside, 'div', {
            role: 'complementary',
            'aria-label': 'Дополнительная информация по запросу',
            className: 'serp-list serp-list_right_yes serp-list_complementary_yes',
            style: `
                padding: 15px;
                border-radius: 10px;
                margin-top: 10px;
                display: block;
                max-width: 90%;
                background-color: ${isDarkMode ? '#0e1011' : '#f9f9f9'};
                border: 2px solid ${isDarkMode ? '#970e05' : '#007BFF'};
                color: ${isDarkMode ? 'white' : 'black'};
            `
        });

        GM_addElement(infoDiv, 'h2', {
            textContent: doc.querySelector('h1').textContent,
            style: `
                margin: 0 0 20px;
                font-size: 18px;
                font-weight: bold;
                color: ${isDarkMode ? '#ffcccc' : '#007BFF'};
            `
        });

        const logo = doc.querySelector('.infobox img');
        if (logo) {
            GM_addElement(infoDiv, 'img', {
                src: logo.src,
                alt: doc.querySelector('h1').textContent,
                style: `
                    max-width: 100px;
                    border-radius: 10px;
                    float: right;
                    margin-left: 10px;
                `
            });
        }

        const contentElements = doc.querySelectorAll('#mw-content-text p');
        contentElements.forEach((element, index) => {
            if (index < 3) {
                GM_addElement(infoDiv, 'p', {
                    textContent: element.textContent,
                    style: `
                        margin-top: 10px;
                        color: ${isDarkMode ? '#e5e5e5' : '#333'};
                    `
                });
            }
        });

        // Источник
        GM_addElement(infoDiv, 'p', {
            textContent: "Источник: Wikipedia",
            style: `
                margin-top: 10px;
                font-size: 12px;
                text-align: right;
                color: ${isDarkMode ? '#e5e5e5' : '#333'};
            `
        });
    }

    function handleNoResults(queryText) {
        console.log('Ничего не найдено:', queryText);
        const queryWithoutSpaces = queryText.replace(/\s+/g, '');
        sendWikipediaRequest(queryWithoutSpaces, function(error, doc) {
            if (!error) {
                console.log('Нашелся результат:', queryWithoutSpaces);
                processWikipediaResponse(doc);
            } else {
                const words = queryText.split(' ');
                for (let word of words) {
                    sendWikipediaRequest(word, function(error, doc) {
                        if (!error) {
                            console.log('Нашелся результат:', word);
                            processWikipediaResponse(doc);
                            return;
                        } else {
                            console.log(`Ничего не найдено для: ${word}`);
                        }
                    });
                }
            }
        });
    }

    function CreateRightBox() {
        const searchResultAside = document.querySelector('#search-result-aside');
        const queryText = new URLSearchParams(window.location.search).get('text');

        if (queryText && queryText.length < 30 && queryText !== lastQuery) {
            lastQuery = queryText;

            sendWikipediaRequest(queryText, function(error, doc) {
                if (!error) {
                    processWikipediaResponse(doc);
                } else {
                    handleNoResults(queryText);
                }
            });
        }
    }

    function checkAndRun() {
        CreateRightBox();
    }

    function observeUrlChanges() {
        let oldHref = document.location.href;

        const body = document.querySelector("body");
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function() {
                if (oldHref !== document.location.href) {
                    oldHref = document.location.href;
                    console.log("URL изменен:", oldHref);
                    setTimeout(checkAndRun, 500);
                }
            });
        });

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

    window.addEventListener('load', () => {
        checkAndRun();
        observeUrlChanges();
    });

})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址