Greasy Fork

Greasy Fork is available in English.

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

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

当前为 2024-03-06 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         一键复制HTML表格/网页代码/latex公式
// @namespace    http://greasyfork.icu/zh-CN/scripts/454641
// @version      0.8.1
// @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        https://c.biancheng.net/*
// @match        https://juejin.cn/*
// @match        https://www.statology.org/*
// @match        https://stats.stackexchange.com/*
// @run-at       document-end
// @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");

    // 设置延迟,防止elements还未创建
    setTimeout(init, 1000);


    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 = "复制成功";
            navigator.clipboard.writeText(markdownResults)
                .then(() => {
                    console.log('文本已经成功复制到剪切板');
                })
                .catch(err => {
                    // 如果用户没有授权,则抛出异常
                    console.error('无法复制此文本:', err);
                });
            // 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;
        navigator.clipboard.writeText(text)
            .then(() => {
                console.log('文本已经成功复制到剪切板');
            })
            .catch(err => {
                // 如果用户没有授权,则抛出异常
                console.error('无法复制此文本:', err);
            });
        // GM.setClipboard(text);
    }

    function copyMathFormula(x) {
        navigator.clipboard.writeText(x.innerText)
            .then(() => {
                console.log('文本已经成功复制到剪切板');
            })
            .catch(err => {
                // 如果用户没有授权,则抛出异常
                console.error('无法复制此文本:', err);
            });
        // GM.setClipboard(x.innerText);
    }

    function createButtons(x, type) {
        [...x].forEach((value, index) => {
            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");
        // 获取使用MathJax渲染的latex公式
        createButtons(document.querySelectorAll('script[type^="math/tex"]'), "Math");

        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");
        }
    }
})();