You.com KaTeX Copy Handler

Clean copy of KaTeX expressions without duplicates or extra line breaks

目前为 2025-04-12 提交的版本。查看 最新版本

// ==UserScript==
// @name         You.com KaTeX Copy Handler
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  Clean copy of KaTeX expressions without duplicates or extra line breaks
// @author       Assistant
// @match        *://*.you.com/*
// @grant        none
// @icon         https://www.google.com/s2/favicons?sz=64&domain=you.com
// @license MIT
// ==/UserScript==

(function() {
    'use strict';

    // Function to extract clean text from a KaTeX element
    function extractKaTeXText(element) {
        // Get the LaTeX source from annotation if available
        const annotation = element.querySelector('.katex-mathml annotation[encoding="application/x-tex"]');
        if (annotation) {
            return annotation.textContent;
        }

        // Fallback: extract from visible content
        const baseElements = element.querySelectorAll('.katex-html .base .mord, .katex-html .base .mopen, .katex-html .base .mclose');
        return Array.from(baseElements).map(el => el.textContent).join('');
    }

    // Function to extract text from a range, handling both KaTeX and regular text
    function extractTextFromRange(range) {
        const fragment = range.cloneContents();
        const nodes = Array.from(fragment.childNodes);
        let result = '';

        nodes.forEach(node => {
            if (node.nodeType === Node.ELEMENT_NODE) {
                // Check if the node is a KaTeX element
                if (node.classList.contains('katex')) {
                    result += extractKaTeXText(node);
                } else {
                    result += node.textContent; // Regular element
                }
            } else if (node.nodeType === Node.TEXT_NODE) {
                result += node.textContent; // Regular text
            }
        });

        return result;
    }

    // Handle copy event
    document.addEventListener('copy', function (e) {
        const selection = window.getSelection();
        if (!selection.rangeCount) return;

        const range = selection.getRangeAt(0);

        // Extract text from the range, handling both KaTeX and regular text
        const cleanText = extractTextFromRange(range);

        // Override the clipboard data
        e.preventDefault();
        e.clipboardData.setData('text/plain', cleanText);
    });



    // Log that script is active
    console.log('KaTeX Copy Handler active');
})();

QingJ © 2025

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