一键复制HTML表格/网页代码/latex公式

在指定网站的表格上方添加按钮,点击将表格以Markdown格式复制到剪贴板

目前为 2024-03-04 提交的版本。查看 最新版本

// ==UserScript==
// @name         一键复制HTML表格/网页代码/latex公式
// @namespace    https://greasyfork.org/zh-CN/scripts/454641
// @version      0.8
// @description  在指定网站的表格上方添加按钮,点击将表格以Markdown格式复制到剪贴板
// @author       lsovaber
// @match        https://blog.csdn.net/*
// @match        https://www.cnblogs.com/*
// @match        https://www.runoob.com/*
// @match        https://www.jianshu.com/*
// @match        https://*.zhihu.com/*
// @match        https://www.quanxiaoha.com/*
// @match        https://www.geeksforgeeks.org/*
// @match        https://online.stat.psu.edu/stat800/*
// @match        https://www.javatpoint.com/*
// @match        https://cloud.tencent.com/*
// @match        https://scikit-learn.org/*
// @match        https://www.w3school.com.cn/*
// @match        https://www.w3cschool.cn/*
// @match        http://c.biancheng.net/*
// @match        https://juejin.cn/*
// @match        https://www.statology.org/*
// @grant        GM.setClipboard
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    const NL = "\n";

    // 存放Markdown表格
    let processor = document.createElement("processor");
    // 获取<table>
    let table = document.getElementsByTagName("table");

    // 大多数网站块代码在<pre>里
    let pre = document.getElementsByTagName("pre");


    setTimeout(init, 500);


    function convertTableElementToMarkdown(tableEl) {
        const rows = [];
        const trEls = tableEl.getElementsByTagName('tr');
        for (let i = 0; i < trEls.length; i++) {
            const tableRow = trEls[i];
            const markdownRow = convertTableRowElementToMarkdown(tableRow, i);
            rows.push(markdownRow);
        }
        return rows.join(NL);
    }

    function convertTableRowElementToMarkdown(tableRowEl, rowNumber) {
        const cells = [];
        const cellEls = tableRowEl.children;
        for (let i = 0; i < cellEls.length; i++) {
            const cell = cellEls[i];
            cells.push(cell.innerText + ' |');
        }
        let row = '| ' + cells.join(" ");

        if (rowNumber === 0) {
            row = row + NL + createMarkdownDividerRow(cellEls.length);
        }

        return row;
    }

    function createMarkdownDividerRow(cellCount) {
        const dividerCells = [];
        for (let i = 0; i < cellCount; i++) {
            dividerCells.push('--- |');
        }
        return '| ' + dividerCells.join(" ");
    }


    function convertTable(x) {
        const content = "<table>" + x.innerHTML + "</table>";
        processor.innerHTML = content.replace(/\s+/g, ' ');

        const tables = processor.getElementsByTagName('table');
        let markdownResults = '';
        if (tables) {
            for (let e of tables) {
                const markdownTable = convertTableElementToMarkdown(e);
                markdownResults += markdownTable + NL + NL;
            }
            let p = document.createElement("p");
            p.innerHTML = "复制成功";
            GM.setClipboard(markdownResults);
            x.parentNode.insertBefore(p, x);
        } else {
            console.log('No table found');
        }
    }

    function copyCode(x) {
        let text = window.location.href.includes("juejin") ? x.innerText.replace(/^.*\n.*复制代码/g, "") : x.innerText;
        GM.setClipboard(text);
    }

    function copyMathFormula(x) {
        GM.setClipboard(x.innerText);
    }

    function createButtons(x, type) {
        [...x].forEach((value, index, array) => {
            let button = document.createElement("button");
            button.innerText = `Copy ${type}`;
            // button.style.zIndex = '999';

            // 点击按钮,进行转化
            button.addEventListener('click', function () {
                if (type === "Table") {
                    convertTable(x[index])
                } else if (type === "Code") {
                    copyCode(x[index])
                } else {
                    copyMathFormula(x[index])
                }
            })
            // button.addEventListener('click', () => type === "Table" ? convertTable(x[index]) : copyCode(x[index]))
            x[index].parentNode.insertBefore(button, x[index]);
        })
    }

    function init() {

        createButtons(table, "Table");
        createButtons(pre, "Code");


        let url = window.location.href
        if (url.includes("runoob")) {
            // 菜鸟教程的代码块
            let example_code = document.getElementsByClassName("example_code");
            createButtons(example_code, "Code");
        } else if (url.includes("cnblogs") || url.includes("www.geeksforgeeks.org")) {
            let cn_blogs = document.getElementsByClassName("code");
            createButtons(cn_blogs, "Code");
        }
        
        // 点击按钮复制latex公式,目前只适配知乎和cnblogs
        let formula;
        if (url.includes("zhihu")) {
            formula = document.querySelectorAll('script[type="math/tex;mode=inline"]');
        } else if (url.includes("cnblogs")) {
            formula = document.querySelectorAll('script[type="math/tex; mode=display"]');
        }

        createButtons(formula, "Math");
    }
})();