Greasy Fork is available in English.
在指定网站的表格上方添加按钮,点击将表格以Markdown格式复制到剪贴板
当前为
// ==UserScript==
// @name HTML表格转化为Markdown表格
// @namespace http://tampermonkey.net/
// @version 0.2
// @description 在指定网站的表格上方添加按钮,点击将表格以Markdown格式复制到剪贴板
// @author You
// @match https://blog.csdn.net/*
// @match https://www.cnblogs.com/*
// @match https://www.runoob.com/*
// @match https://www.jianshu.com/*
// @match https://www.zhihu.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=csdn.net
// @grant none
// @license MIT
// ==/UserScript==
(function() {
'use strict';
const NL = "\n";
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(() => {
x.parentNode.insertBefore(p, x)
})
.catch(err => {
p.innerHTML = "复制失败" + err;
x.parentNode.insertBefore(p, x)
});
}
else {
console.log('No table found');
}
}
let processor = document.createElement("processor");
let x = document.getElementsByTagName("table")
for (let i = 0; i < x.length; i++){
let button = document.createElement("button");
button.innerText = "Copy";
button.addEventListener('click', function () {
convertTable(x[i])
})
x[i].parentNode.insertBefore(button, x[i])
}
})();