*/
document.querySelectorAll('picture source[srcset]').forEach(function (sc) {
var first = (sc.getAttribute('srcset') || '').split(',')[0];
if (first) push(first.trim().split(/\s+/)[0], 0, 0, 'picture');
});
/* CSS 背景图(限前 120 个元素,避免卡) */
var all = document.querySelectorAll('*');
for (var k = 0; k < all.length && k < 1200 && out.length < 200; k++) {
var bg = '';
try { bg = getComputedStyle(all[k]).backgroundImage || ''; } catch (e) { bg = ''; }
var m = /url\(["']?([^"')]+)["']?\)/.exec(bg);
if (m && m[1]) push(m[1], 0, 0, 'bg');
}
return out;
}
/* --- 极简 ZIP(仅存储不压缩)--- */
var CRC_TABLE = (function () {
var t = new Uint32Array(256);
for (var n = 0; n < 256; n++) {
var c = n;
for (var k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
t[n] = c >>> 0;
}
return t;
})();
function crc32(buf) {
var c = 0xFFFFFFFF;
for (var i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8);
return (c ^ 0xFFFFFFFF) >>> 0;
}
function makeZip(files) {
var enc = new TextEncoder();
var parts = [], central = [], offset = 0;
files.forEach(function (f) {
var name = enc.encode(f.name);
var data = f.data;
var crc = crc32(data);
var local = new Uint8Array(30 + name.length);
var dv = new DataView(local.buffer);
dv.setUint32(0, 0x04034b50, true);
dv.setUint16(4, 20, true);
dv.setUint16(6, 0x0800, true);
dv.setUint16(8, 0, true);
dv.setUint16(10, 0, true);
dv.setUint16(12, 0, true);
dv.setUint32(14, crc, true);
dv.setUint32(18, data.length, true);
dv.setUint32(22, data.length, true);
dv.setUint16(26, name.length, true);
dv.setUint16(28, 0, true);
local.set(name, 30);
parts.push(local, data);
var cd = new Uint8Array(46 + name.length);
var cv = new DataView(cd.buffer);
cv.setUint32(0, 0x02014b50, true);
cv.setUint16(4, 20, true);
cv.setUint16(6, 20, true);
cv.setUint16(8, 0x0800, true);
cv.setUint16(10, 0, true);
cv.setUint16(12, 0, true);
cv.setUint16(14, 0, true);
cv.setUint32(16, crc, true);
cv.setUint32(20, data.length, true);
cv.setUint32(24, data.length, true);
cv.setUint16(28, name.length, true);
cv.setUint16(30, 0, true);
cv.setUint16(32, 0, true);
cv.setUint16(34, 0, true);
cv.setUint16(36, 0, true);
cv.setUint32(38, 0, true);
cv.setUint32(42, offset, true);
cd.set(name, 46);
central.push(cd);
offset += local.length + data.length;
});
var cdSize = central.reduce(function (a, b) { return a + b.length; }, 0);
var end = new Uint8Array(22);
var ev = new DataView(end.buffer);
ev.setUint32(0, 0x06054b50, true);
ev.setUint16(8, files.length, true);
ev.setUint16(10, files.length, true);
ev.setUint32(12, cdSize, true);
ev.setUint32(16, offset, true);
return new Blob(parts.concat(central, [end]), { type: 'application/zip' });
}
function saveBlob(blob, name) {
var a = document.createElement('a');
var u = URL.createObjectURL(blob);
a.href = u;
a.download = name;
document.body.appendChild(a);
a.click();
setTimeout(function () { URL.revokeObjectURL(u); a.remove(); }, 4000);
}
function fileName(u, i) {
var n = 'image_' + (i + 1);
try {
var p = new URL(u).pathname.split('/').pop();
if (p && p.length < 80) n = decodeURIComponent(p).replace(/[\\/:*?"<>|]/g, '_');
} catch (e) {}
if (!/\.(jpg|jpeg|png|webp|gif|bmp|avif)$/i.test(n)) n += '.jpg';
return n;
}
/* 逐个抓取;跨域失败就退回新窗口打开 */
async function grab(url) {
try {
var r = await fetch(url, { credentials: 'omit', mode: 'cors' });
if (!r.ok) throw new Error('HTTP ' + r.status);
return new Uint8Array(await r.arrayBuffer());
} catch (e) {
return null;
}
}
var IMG = { list: [], sel: {}, panel: null, busy: false };
function imgPanel() {
if (IMG.panel) { IMG.panel.remove(); IMG.panel = null; return; }
IMG.list = collectImages();
IMG.sel = {};
if (!IMG.list.length) { toast('本页没找到图片'); return; }
var box = document.createElement('div');
box.style.cssText = 'position:fixed;inset:4% 6%;z-index:2147483003;background:#fff;border-radius:16px;' +
'box-shadow:0 20px 60px rgba(0,0,0,.35);display:flex;flex-direction:column;overflow:hidden;' +
'font:13px/1.6 -apple-system,"Segoe UI",sans-serif;color:#1c1c1e';
box.innerHTML =
'' +
'图片原图下载' +
'' +
'' +
'' +
'' +
'' +
'' +
'
';
var list = box.querySelector('#cf-list');
IMG.list.forEach(function (it, i) {
var card = document.createElement('div');
card.style.cssText = 'border:2px solid ' + (it.orig !== it.url ? '#34c759' : '#e5e5ea') +
';border-radius:10px;overflow:hidden;cursor:pointer;background:#fafafa';
var thumb = document.createElement('img');
thumb.src = it.url;
thumb.style.cssText = 'width:100%;height:96px;object-fit:cover;display:block;background:#eee';
var meta = document.createElement('div');
meta.style.cssText = 'padding:6px 8px;font-size:11px;color:#666;white-space:nowrap;overflow:hidden;text-overflow:ellipsis';
meta.textContent = (it.w ? it.w + '×' + it.h : '尺寸未知') +
(it.orig !== it.url ? ' · 可还原原图' : '') + (it.note ? ' · ' + it.note : '');
card.appendChild(thumb);
card.appendChild(meta);
card.onclick = function () {
if (IMG.sel[i]) { delete IMG.sel[i]; card.style.outline = ''; }
else { IMG.sel[i] = 1; card.style.outline = '3px solid #0a84ff'; }
updateCnt();
};
list.appendChild(card);
});
function updateCnt() {
var n = Object.keys(IMG.sel).length;
box.querySelector('#cf-cnt').textContent = '共 ' + IMG.list.length + ' 张 · 已选 ' + n;
}
updateCnt();
box.querySelector('#cf-x').onclick = function () { box.remove(); IMG.panel = null; };
box.querySelector('#cf-all').onclick = function () {
var all = Object.keys(IMG.sel).length !== IMG.list.length;
IMG.sel = {};
if (all) IMG.list.forEach(function (_, i) { IMG.sel[i] = 1; });
Array.prototype.forEach.call(list.children, function (c, i) {
c.style.outline = IMG.sel[i] ? '3px solid #0a84ff' : '';
});
updateCnt();
};
box.querySelector('#cf-copy').onclick = function () {
var urls = Object.keys(IMG.sel).map(function (i) { return IMG.list[i].orig; });
if (!urls.length) return toast('先选几张');
var txt = urls.join('\n');
if (navigator.clipboard) navigator.clipboard.writeText(txt).then(function () { toast('已复制 ' + urls.length + ' 条'); });
else toast('复制失败');
};
box.querySelector('#cf-zip').onclick = async function () {
var idx = Object.keys(IMG.sel).map(Number);
if (!idx.length) return toast('先选择图片');
if (IMG.busy) return;
IMG.busy = true;
toast('正在抓取 0/' + idx.length + '…');
var files = [], fail = 0;
for (var n = 0; n < idx.length; n++) {
var it = IMG.list[idx[n]];
var data = await grab(it.orig);
if (!data) { fail++; continue; }
files.push({ name: fileName(it.orig, n), data: data });
toast('正在抓取 ' + (n + 1) + '/' + idx.length + '…');
}
IMG.busy = false;
if (!files.length) return toast('全部抓取失败(跨域限制),可改用「复制链接」');
saveBlob(makeZip(files), 'images_' + Date.now() + '.zip');
toast('已打包 ' + files.length + ' 张' + (fail ? '(' + fail + ' 张跨域失败)' : ''));
};
document.body.appendChild(box);
IMG.panel = box;
}
/* ---------- 7) 正文提取复制 ---------- */
/* 思路:候选容器打分(文字长度 / 段落数 / 链接密度 / 类名特征),取最高分当正文 */
var NEG_CLASS = /(nav|menu|header|footer|sidebar|aside|comment|advert|banner|promo|share|related|recommend|breadcrumb|copyright|toolbar|popup|modal|login)/i;
var POS_CLASS = /(article|content|post|entry|main|body|text|detail|rich|markdown|read)/i;
function cleanText(t) {
return String(t || '')
.replace(/[ \t\u00a0]+/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
function textOf(el) {
var t = '';
try { t = el.innerText || el.textContent || ''; } catch (e) { t = ''; }
return cleanText(t);
}
function scoreNode(el) {
var txt = textOf(el);
if (txt.length < 140) return -1;
var links = el.querySelectorAll('a');
var linkLen = 0;
for (var i = 0; i < links.length; i++) linkLen += (links[i].innerText || '').length;
var density = links.length ? linkLen / Math.max(1, txt.length) : 0;
if (density > 0.55) return -1; /* 链接太多 = 导航区 */
var cls = String(el.className || '') + ' ' + String(el.id || '');
var score = txt.length;
if (POS_CLASS.test(cls)) score *= 1.6;
if (NEG_CLASS.test(cls)) score *= 0.35;
var paras = el.querySelectorAll('p,div>br,li').length;
score *= 1 + Math.min(1.2, paras / 40);
score *= 1 - density; /* 链接密度越高越不像正文 */
/* 太靠近 body/html 的容器扣分(避免整页) */
if (el === document.body) score *= 0.25;
if (el.tagName === 'HTML') score *= 0.1;
return score;
}
function pickContentNode() {
var best = null, bestScore = 0;
var cands = document.querySelectorAll(
'article, main, [class*="article"], [class*="content"], [class*="post"], [class*="entry"],' +
'[class*="detail"], [class*="rich"], [id*="content"], [id*="article"], .markdown-body, section, div'
);
var limit = Math.min(cands.length, 2500);
for (var i = 0; i < limit; i++) {
var el = cands[i];
try {
var cs = getComputedStyle(el);
if (cs.display === 'none' || cs.visibility === 'hidden') continue;
} catch (e) {}
var s = scoreNode(el);
if (s > bestScore) { bestScore = s; best = el; }
}
return best;
}
/* 克隆并剔除明显噪音(正文/Markdown 共用) */
function cleanClone(root) {
var clone = root.cloneNode(true);
clone.querySelectorAll('script,style,noscript,svg,canvas,iframe,video,audio,form,nav,aside,footer,header,[aria-hidden="true"]')
.forEach(function (n) { try { n.remove(); } catch (e) {} });
clone.querySelectorAll('[class],[id]').forEach(function (n) {
try {
var c = String(n.className || '') + ' ' + String(n.id || '');
if (NEG_CLASS.test(c) && textOf(n).length < 400) n.remove();
} catch (e) {}
});
return clone;
}
/* 从正文节点里提取结构化纯文本:段落换行、标题保留 */
function extractText(root) {
if (!root) return '';
var clone = cleanClone(root);
/* 块级元素前后补换行 */
var out = [];
(function walk(node) {
if (!node) return;
if (node.nodeType === 3) {
var t = node.nodeValue;
if (t && t.trim()) out.push(t.replace(/[ \t\u00a0]+/g, ' '));
return;
}
if (node.nodeType !== 1) return;
var tag = node.tagName;
if (tag === 'BR') { out.push('\n'); return; }
var block = /^(P|DIV|SECTION|ARTICLE|LI|TR|H1|H2|H3|H4|H5|H6|BLOCKQUOTE|PRE|TD|DD|DT)$/.test(tag);
if (block) out.push('\n');
if (/^H[1-6]$/.test(tag)) out.push('\n');
var kids = node.childNodes;
for (var i = 0; i < kids.length; i++) walk(kids[i]);
if (block) out.push('\n');
})(clone);
var text = out.join('').replace(/[ \t\u00a0]+/g, ' ').replace(/\n\s*\n\s*\n+/g, '\n\n').trim();
return text;
}
function copyText(txt) {
if (!txt) return false;
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(txt);
return true;
}
} catch (e) {}
try {
var ta = document.createElement('textarea');
ta.value = txt;
ta.style.cssText = 'position:fixed;left:-9999px';
document.body.appendChild(ta);
ta.select();
var ok = document.execCommand('copy');
ta.remove();
return ok;
} catch (e) { return false; }
}
/* 一键复制全文 */
function copyArticle(silent) {
var root = pickContentNode();
var txt = extractText(root);
if (!txt || txt.length < 80) {
toast('没找到正文(可能这页不是文章)');
return false;
}
var ok = copyText(txt);
if (ok && !silent) toast('已复制正文 ' + txt.length + ' 字');
else if (!ok) toast('复制失败,请手动选中');
return ok ? txt : false;
}
/* 正文预览面板:可编辑后再复制 */
function articlePanel() {
var root = pickContentNode();
var txt = extractText(root);
if (!txt || txt.length < 80) { toast('没找到正文'); return; }
var old = document.getElementById('cf-article');
if (old) { old.remove(); return; }
var box = document.createElement('div');
box.id = 'cf-article';
box.style.cssText = 'position:fixed;inset:6% 8%;z-index:2147483003;background:#fff;border-radius:16px;' +
'box-shadow:0 20px 60px rgba(0,0,0,.35);display:flex;flex-direction:column;overflow:hidden;' +
'font:13px/1.7 -apple-system,"Segoe UI",sans-serif;color:#1c1c1e';
box.innerHTML =
'' +
'正文提取' +
'' +
'' +
'' +
'' +
'' +
'
' +
'';
var ta = box.querySelector('#cf-text');
ta.value = txt;
box.querySelector('#cf-len').textContent = txt.length + ' 字 · ' + txt.split('\n').filter(function (x) { return x.trim(); }).length + ' 段';
box.querySelector('#cf-copy2').onclick = function () {
if (copyText(ta.value)) toast('已复制 ' + ta.value.length + ' 字');
else toast('复制失败');
};
box.querySelector('#cf-txt').onclick = function () {
var name = (document.title || 'article').replace(/[\\/:*?"<>|]/g, '_').slice(0, 60) + '.txt';
saveBlob(new Blob([ta.value], { type: 'text/plain;charset=utf-8' }), name);
toast('已保存 ' + name);
};
box.querySelector('#cf-x2').onclick = function () { box.remove(); };
document.body.appendChild(box);
}
/* ---------- 8) 表格解析与导出 ---------- */
function cellText(td) {
var t = '';
try { t = td.innerText; } catch (e) {}
if (!t) t = td.textContent || '';
return String(t).replace(/\s+/g, ' ').trim();
}
/* 把表格展开成二维网格:rowspan / colspan 都补成占位空格,保证行列对齐 */
function tableGrid(table) {
var trs = table.querySelectorAll('tr');
var grid = [], pend = {}, maxCols = 0;
for (var i = 0; i < trs.length; i++) {
var cells = trs[i].children, row = [], col = 0;
for (var j = 0; j < cells.length; j++) {
var c = cells[j];
if (!/^(TD|TH)$/.test(c.tagName)) continue;
/* 先占掉上方 rowspan 遗留的格子 */
while (pend[col] > 0) { row[col] = ''; pend[col]--; col++; }
var cs = parseInt(c.getAttribute('colspan') || '1', 10) || 1;
var rs = parseInt(c.getAttribute('rowspan') || '1', 10) || 1;
row[col] = cellText(c);
for (var k = 1; k < cs; k++) row[col + k] = '';
if (rs > 1) { for (var k2 = 0; k2 < cs; k2++) pend[col + k2] = rs - 1; }
col += cs;
}
/* 行尾还可能挂着 rowspan 的占位 */
while (pend[col] > 0) { row[col] = ''; pend[col]--; col++; }
for (var m = 0; m < row.length; m++) { if (row[m] == null) row[m] = ''; }
if (row.length) {
grid.push(row);
if (row.length > maxCols) maxCols = row.length;
}
}
/* 统一列宽,补齐短板 */
for (var r = 0; r < grid.length; r++) {
while (grid[r].length < maxCols) grid[r].push('');
}
return grid;
}
function csvEscape(v) {
var s = String(v == null ? '' : v);
if (/[",\n\r]/.test(s)) return '"' + s.replace(/"/g, '""') + '"';
return s;
}
/* CSV:BOM + CRLF,Excel 打开中文不乱码 */
function gridToCsv(grid) {
var rows = grid.map(function (line) { return line.map(csvEscape).join(','); });
return '\ufeff' + rows.join('\r\n');
}
function gridToTsv(grid) {
return grid.map(function (line) {
return line.map(function (v) {
return String(v == null ? '' : v).replace(/\t/g, ' ').replace(/\r?\n/g, ' ');
}).join('\t');
}).join('\r\n');
}
/* Markdown 表格:首行当表头 */
function gridToMd(grid) {
if (!grid.length) return '';
var cols = grid[0].length;
var cell = function (v) {
return String(v == null ? '' : v).replace(/\r?\n/g, ' ').replace(/\|/g, '\\|').trim();
};
var out = ['| ' + grid[0].map(cell).join(' | ') + ' |',
'|' + new Array(cols + 1).join(' --- |')];
for (var i = 1; i < grid.length; i++) {
var blank = grid[i].every(function (x) { return !String(x || '').trim(); });
if (blank) continue;
out.push('| ' + grid[i].map(cell).join(' | ') + ' |');
}
return out.join('\n') + '\n';
}
/* JSON:首行当字段名,重名自动加后缀 */
function gridToJson(grid) {
if (!grid.length) return '[]';
var seen = {};
var head = grid[0].map(function (h, i) {
var t = String(h || '').trim() || ('col' + (i + 1));
if (seen[t]) { seen[t]++; return t + '_' + seen[t]; }
seen[t] = 1;
return t;
});
var arr = [];
for (var i = 1; i < grid.length; i++) {
var o = {}, blank = true;
for (var j = 0; j < head.length; j++) {
var v = grid[i][j] == null ? '' : String(grid[i][j]);
if (v.trim()) blank = false;
o[head[j]] = v;
}
if (!blank) arr.push(o);
}
return JSON.stringify(arr, null, 2);
}
function exportTableAs(table, idx, fmt) {
var grid = tableGrid(table);
if (!grid.length || !grid[0].length) { toast('这个表格没内容'); return; }
var base = 'table_' + (idx + 1) + '_' + new Date().toISOString().slice(0, 10);
var text = '', name = base, mime = 'text/plain;charset=utf-8';
if (fmt === 'tsv') { text = gridToTsv(grid); name += '.tsv'; }
else if (fmt === 'md') { text = gridToMd(grid); name += '.md'; mime = 'text/markdown;charset=utf-8'; }
else if (fmt === 'json') { text = gridToJson(grid); name += '.json'; mime = 'application/json;charset=utf-8'; }
else { text = gridToCsv(grid); name += '.csv'; mime = 'text/csv;charset=utf-8'; }
saveBlob(new Blob([text], { type: mime }), name);
toast('已导出 ' + grid.length + ' 行 → ' + name);
}
/* 兼容旧入口 */
function exportTable(table, idx) {
exportTableAs(table, idx, 'csv');
}
/* 格式选择浮层 */
function fmtMenu(ev, table, idx) {
var old = document.getElementById('cf-fmt');
if (old) old.remove();
var m = document.createElement('div');
m.id = 'cf-fmt';
var x = Math.max(8, Math.min((ev.clientX || 40) - 60, window.innerWidth - 152));
var y = Math.max(8, Math.min((ev.clientY || 40), window.innerHeight - 186));
m.style.cssText = 'position:fixed;left:' + x + 'px;top:' + y + 'px;z-index:2147483006;background:#fff;' +
'border:.5px solid rgba(0,0,0,.08);border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,.22);' +
'padding:6px;min-width:140px;font:13px/1.5 -apple-system,"Segoe UI",sans-serif;color:#1c1c1e';
[['CSV', 'csv', 'Excel 通用(带 BOM 不乱码)'],
['Markdown', 'md', '贴笔记 / 文档'],
['JSON', 'json', '首行当字段名'],
['TSV', 'tsv', '制表符分隔']].forEach(function (it) {
var b = document.createElement('button');
b.textContent = it[0];
b.title = it[2];
b.style.cssText = 'display:block;width:100%;text-align:left;border:none;background:transparent;' +
'border-radius:7px;padding:7px 10px;cursor:pointer;color:#1c1c1e;' +
'font:13px/1.4 -apple-system,"Segoe UI",sans-serif';
b.onmouseenter = function () { b.style.background = '#f2f2f7'; };
b.onmouseleave = function () { b.style.background = 'transparent'; };
b.onclick = function (e2) {
e2.preventDefault();
e2.stopPropagation();
m.remove();
exportTableAs(table, idx, it[1]);
};
m.appendChild(b);
});
document.body.appendChild(m);
setTimeout(function () {
var close = function (e3) {
if (!m.contains(e3.target)) { m.remove(); document.removeEventListener('mousedown', close, true); }
};
document.addEventListener('mousedown', close, true);
}, 0);
}
/* 给页面上每个表格挂一个「导出」角标 */
function markTables() {
var tables = document.querySelectorAll('table');
for (var i = 0; i < tables.length; i++) {
var t = tables[i];
try {
if (t.dataset.cfMark === '1') continue;
var rows = t.querySelectorAll('tr').length;
if (rows < 2) continue; /* 单行表格跳过(多是布局表格) */
var cols = 0;
var firstTr = t.querySelector('tr');
if (firstTr) cols = firstTr.children.length;
if (cols < 2 && rows < 3) continue;
} catch (e) { continue; }
try { t.dataset.cfMark = '1'; } catch (e) {}
var btn = document.createElement('button');
btn.textContent = '导出 ▾';
btn.style.cssText = 'position:absolute;right:6px;top:6px;z-index:2147482000;' +
'background:#34c759;color:#fff;border:none;border-radius:7px;padding:4px 9px;' +
'font:600 11px/1.4 -apple-system,"Segoe UI",sans-serif;cursor:pointer;' +
'box-shadow:0 4px 12px rgba(52,199,89,.35);opacity:.92';
btn.onclick = function (ev) {
ev.preventDefault();
ev.stopPropagation();
fmtMenu(ev, this._cfTable, this._cfIdx);
return false;
};
btn._cfTable = t;
btn._cfIdx = i;
/* 表格容器加 relative,保证角标定位在表格右上角 */
var wrap = t.parentElement;
try {
var pos = getComputedStyle(wrap).position;
if (pos === 'static') wrap.style.position = 'relative';
wrap.appendChild(btn);
} catch (e) {
try { t.appendChild(btn); } catch (e2) {}
}
}
}
/* ---------- 9) Markdown 转换器(零依赖手写) ---------- */
/* 思路:一次性递归。块级元素各返回一段字符串,行内元素拼成一串,父层负责拼接和空行压缩。 */
var MD_BLOCK_TAG = /^(ADDRESS|ARTICLE|ASIDE|BLOCKQUOTE|DD|DETAILS|DIV|DL|DT|FIELDSET|FIGCAPTION|FIGURE|FOOTER|FORM|H[1-6]|HEADER|HR|LI|MAIN|NAV|OL|P|PRE|SECTION|SUMMARY|TABLE|UL)$/;
var MD_SKIP_TAG = /^(SCRIPT|STYLE|NOSCRIPT|SVG|CANVAS|IFRAME|OBJECT|EMBED|VIDEO|AUDIO|BUTTON|INPUT|SELECT|TEXTAREA|LINK|META|TEMPLATE|BASE)$/;
/* 纯文本转义:只转义会破坏结构的字符,中文正文基本不受影响 */
function mdText(s) {
return String(s).replace(/[\\`*_\[\]<>]/g, function (m) { return '\\' + m; });
}
/* 行首如果是 # > + - 1. 会被当成语法,转义掉 */
function mdEscLineStart(s) {
return String(s).replace(/^([ \t]*)([#>+\-]|\d+\.)([ \t])/gm, function (all, a, b, c) {
return a + '\\' + b + c;
});
}
/* 代码块围栏:内容里若本身有 ``` 就加长围栏 */
function mdFence(text) {
var n = 3, m = String(text).match(/`{3,}/g);
if (m) for (var i = 0; i < m.length; i++) if (m[i].length >= n) n = m[i].length + 1;
return new Array(n + 1).join('`');
}
/* 行内代码:反引号个数自适应 */
function mdInlineCode(t) {
var s = String(t).replace(/\n+/g, ' ');
var max = 0, m = s.match(/`+/g);
if (m) for (var i = 0; i < m.length; i++) max = Math.max(max, m[i].length);
var f = new Array(max + 2).join('`');
var pad = (max > 0 && (/^`/.test(s) || /`$/.test(s))) ? ' ' : '';
return f + pad + s + pad + f;
}
/* 强调包裹:首尾空格要留在标记外面,否则不生效 */
function mdWrap(s, mark) {
var raw = String(s || '');
if (!raw) return '';
var lead = /^\s/.test(raw) ? ' ' : '';
var tail = /\s$/.test(raw) ? ' ' : '';
var t = raw.trim();
if (!t) return raw;
if (/\n{2,}/.test(t)) return lead + t + tail; /* 块内容不能套强调 */
return lead + mark + t + mark + tail;
}
function mdImage(el) {
var src = el.getAttribute('data-original') || el.getAttribute('data-src') ||
el.getAttribute('data-actualsrc') || el.currentSrc || el.getAttribute('src') || '';
if (!src || /^data:/i.test(src)) return '';
var u = absUrl(src);
if (!u) return '';
var alt = String(el.getAttribute('alt') || '').replace(/[\[\]\n]/g, ' ');
return '/g, '%29').replace(/\s/g, '%20') + ')';
}
/* 行内节点 → 字符串 */
function mdInlineNode(n) {
if (!n) return '';
if (n.nodeType === 3) return mdText(String(n.nodeValue).replace(/\s+/g, ' '));
if (n.nodeType !== 1) return '';
var tag = n.tagName;
if (MD_SKIP_TAG.test(tag)) return '';
if (n.getAttribute && n.getAttribute('aria-hidden') === 'true') return '';
if (tag === 'BR') return ' \n';
if (tag === 'IMG') return mdImage(n);
if (tag === 'CODE' || tag === 'KBD' || tag === 'SAMP' || tag === 'TT') return mdInlineCode(n.textContent || '');
if (tag === 'STRONG' || tag === 'B') return mdWrap(mdInline(n), '**');
if (tag === 'EM' || tag === 'I' || tag === 'CITE') return mdWrap(mdInline(n), '*');
if (tag === 'DEL' || tag === 'S' || tag === 'STRIKE') return mdWrap(mdInline(n), '~~');
if (tag === 'A') {
var href = n.getAttribute('href') || '';
var txt = mdInline(n).replace(/\s+/g, ' ').trim();
if (!href || /^(javascript:|#)/i.test(href)) return txt;
var u = absUrl(href); /* 相对路径必须绝对化,否则 MD 里链接是死的 */
if (!u) return txt;
if (!txt || txt === u) return '<' + u + '>';
return '[' + txt + '](' + u.replace(/\)/g, '%29').replace(/\s/g, '%20') + ')';
}
if (MD_BLOCK_TAG.test(tag)) {
var b = mdBlock(n, 0); /* 行内上下文里冒出块元素,兜一下 */
return b ? '\n\n' + b + '\n\n' : '';
}
return mdInline(n);
}
/* 行内串联 */
function mdInline(node) {
var out = '', kids = node.childNodes, n = kids.length;
for (var i = 0; i < n; i++) out += mdInlineNode(kids[i]);
return out;
}
/* 子节点混合内容 → 段落数组拼成整段 */
function mdChildren(node, depth) {
var parts = [], buf = '';
var kids = node.childNodes, len = kids.length;
var i, n;
for (i = 0; i < len; i++) {
n = kids[i];
if (n.nodeType === 1 && MD_BLOCK_TAG.test(n.tagName)) {
var t = buf.trim();
if (t) parts.push(mdEscLineStart(t));
buf = '';
var b = mdBlock(n, depth || 0);
if (b) parts.push(b);
} else {
buf += mdInlineNode(n);
}
}
var tail = buf.trim();
if (tail) parts.push(mdEscLineStart(tail));
return parts.join('\n\n');
}
/* 代码块 */
function mdPre(el) {
var codeEl = el.querySelector ? el.querySelector('code') : null;
var src = codeEl || el;
var text = String(src.textContent || '').replace(/\r\n?/g, '\n').replace(/^\n+/, '').replace(/\n+$/, '');
if (!text.trim()) return '';
var lang = detectLang(el);
var f = mdFence(text);
return f + (lang || '') + '\n' + text + '\n' + f;
}
/* 列表:负责嵌套缩进,marker 宽度决定续行缩进 */
function mdList(el, depth) {
var ordered = el.tagName === 'OL';
var pad = new Array((depth || 0) + 1).join(' ');
var start = parseInt(el.getAttribute('start') || '1', 10);
if (!start || start < 0) start = 1;
var out = [], idx = 0, kids = el.children, i, j;
for (i = 0; i < kids.length; i++) {
var li = kids[i];
if (li.tagName !== 'LI') continue;
idx++;
var marker = ordered ? (start + idx - 1) + '. ' : '- ';
var contIndent = pad + new Array(marker.length + 1).join(' ');
var inline = '', nested = [];
var kids2 = li.childNodes, klen = kids2.length;
for (j = 0; j < klen; j++) {
var cn = kids2[j];
if (cn.nodeType === 1 && (cn.tagName === 'UL' || cn.tagName === 'OL')) {
nested.push(mdList(cn, (depth || 0) + 1));
} else if (cn.nodeType === 1 && MD_BLOCK_TAG.test(cn.tagName)) {
var b = mdBlock(cn, 0);
if (b) inline += (inline ? '\n\n' : '') + b;
} else {
inline += mdInlineNode(cn);
}
}
var body = inline.replace(/[ \t]+/g, ' ').trim();
var lines = body ? body.split('\n') : [''];
var block = pad + marker + lines[0];
for (j = 1; j < lines.length; j++) {
var ln = lines[j].replace(/^[ \t]+/, '');
block += '\n' + (ln ? contIndent + ln : '');
}
if (nested.length) block += '\n' + nested.join('\n');
out.push(block);
}
return out.join('\n');
}
/* 表格 → Markdown 表格 */
function mdTable(el) {
var grid = tableGrid(el);
if (!grid.length) return '';
return gridToMd(grid).replace(/\n$/, '');
}
/* 块级节点 → 字符串 */
function mdBlock(el, depth) {
var tag = el.tagName;
if (MD_SKIP_TAG.test(tag)) return '';
if (tag === 'PRE') return mdPre(el);
if (tag === 'HR') return '---';
if (/^H[1-6]$/.test(tag)) {
var t = mdInline(el).replace(/\s+/g, ' ').trim();
return t ? new Array(parseInt(tag.charAt(1), 10) + 1).join('#') + ' ' + t : '';
}
if (tag === 'UL' || tag === 'OL') return mdList(el, depth || 0);
if (tag === 'TABLE') return mdTable(el);
if (tag === 'BLOCKQUOTE') {
var inner = mdChildren(el, depth);
if (!inner) return '';
return inner.split('\n').map(function (l) { return l ? '> ' + l : '>'; }).join('\n');
}
return mdChildren(el, depth);
}
/* 收尾:压掉多余空行 */
function mdNorm(s) {
return String(s)
.replace(/\r\n?/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.replace(/^\n+/, '')
.replace(/\s+$/, '');
}
function nowStr() {
var d = new Date();
var p = function (n) { return (n < 10 ? '0' : '') + n; };
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) +
' ' + p(d.getHours()) + ':' + p(d.getMinutes());
}
/* 选中 → Markdown */
function mdFromSelection() {
var sel = window.getSelection ? window.getSelection() : null;
if (!sel || !sel.rangeCount || sel.isCollapsed) return '';
var md = '';
for (var i = 0; i < sel.rangeCount; i++) {
var frag = null;
try { frag = sel.getRangeAt(i).cloneContents(); } catch (e) { continue; } /* 拿到的是 DocumentFragment */
if (!frag || !frag.childNodes.length) continue;
var part = mdChildren(frag, 0);
if (part) md += (md ? '\n\n' : '') + part;
}
return mdNorm(md);
}
/* 整页正文 → Markdown(带来源头) */
function pageMarkdown() {
var root = pickContentNode();
if (!root) return '';
var clone = cleanClone(root);
var body = mdNorm(mdBlock(clone, 0));
if (!body || body.length < 40) return '';
var title = String(document.title || '').trim().replace(/[\[\]]/g, '');
if (!title) { try { title = location.hostname || location.href || ''; } catch (e) { title = ''; } }
var head = '> 来源:[' + title + '](' + location.href + ')\n> 抓取时间:' + nowStr() + '\n\n';
return head + body + '\n';
}
/* 通用文本结果面板(MD 用) */
function mdPanel(md, title) {
var old = document.getElementById('cf-md');
if (old) old.remove();
var box = document.createElement('div');
box.id = 'cf-md';
box.style.cssText = 'position:fixed;inset:5% 7%;z-index:2147483003;background:#fff;border-radius:16px;' +
'box-shadow:0 20px 60px rgba(0,0,0,.35);display:flex;flex-direction:column;overflow:hidden;' +
'font:13px/1.7 -apple-system,"Segoe UI",sans-serif;color:#1c1c1e';
box.innerHTML =
'' +
'' + title + '' +
'' +
'' +
'' +
'' +
'' +
'
' +
'';
var ta = box.querySelector('#cf-mdtext');
ta.value = md;
box.querySelector('#cf-mdlen').textContent = md.length + ' 字 · ' + md.split('\n').length + ' 行';
box.querySelector('#cf-mdcopy').onclick = function () {
if (copyText(ta.value)) toast('已复制 Markdown ' + ta.value.length + ' 字');
else toast('复制失败');
};
box.querySelector('#cf-mdsave').onclick = function () {
var name = (document.title || 'page').replace(/[\\/:*?"<>|]/g, '_').slice(0, 60) + '.md';
saveBlob(new Blob([ta.value], { type: 'text/markdown;charset=utf-8' }), name);
toast('已保存 ' + name);
};
box.querySelector('#cf-mdx').onclick = function () { box.remove(); };
document.body.appendChild(box);
}
/* Alt+M:选中转 Markdown */
function copySelectionMd() {
var md = mdFromSelection();
if (!md) { toast('先选中要转换的内容'); return false; }
if (!copyText(md)) { toast('复制失败,请手动选中'); return false; }
toast('已复制 Markdown · ' + md.length + ' 字');
return md;
}
function pageMdPanel() {
toast('正在转换…');
setTimeout(function () {
var md = '';
try { md = pageMarkdown(); } catch (e) { md = ''; }
if (!md) { toast('没找到正文(可能这页不是文章)'); return; }
mdPanel(md, '整页转 Markdown');
}, 30);
}
/* ---------- 10) 代码块提取 ---------- */
var LANG_ALIAS = {
js: 'javascript', javascript: 'javascript', mjs: 'javascript', cjs: 'javascript',
jsx: 'jsx', ts: 'typescript', typescript: 'typescript', tsx: 'tsx',
py: 'python', python: 'python', py3: 'python',
sh: 'bash', shell: 'bash', bash: 'bash', zsh: 'bash', console: 'bash', shellcheck: 'bash',
ps: 'powershell', ps1: 'powershell', powershell: 'powershell',
html: 'html', htm: 'html', xml: 'xml', svg: 'xml', vue: 'vue',
css: 'css', scss: 'scss', sass: 'scss', less: 'less',
json: 'json', jsonc: 'json', yml: 'yaml', yaml: 'yaml',
md: 'markdown', markdown: 'markdown',
sql: 'sql', mysql: 'sql',
java: 'java', kotlin: 'kotlin', kt: 'kotlin', groovy: 'groovy', scala: 'scala',
go: 'go', golang: 'go', rs: 'rust', rust: 'rust',
c: 'c', h: 'c', cpp: 'cpp', 'c++': 'cpp', cc: 'cpp', hpp: 'cpp',
cs: 'csharp', csharp: 'csharp', 'c#': 'csharp',
php: 'php', rb: 'ruby', ruby: 'ruby', swift: 'swift', dart: 'dart', lua: 'lua', r: 'r',
matlab: 'matlab', dockerfile: 'dockerfile', docker: 'dockerfile', nginx: 'nginx',
ini: 'ini', conf: 'ini', toml: 'toml', bat: 'batch', cmd: 'batch',
diff: 'diff', patch: 'diff', makefile: 'makefile', make: 'makefile',
objc: 'objectivec', objectivec: 'objectivec', erl: 'erlang', ex: 'elixir',
vim: 'vim', tex: 'latex', latex: 'latex', graphql: 'graphql', proto: 'protobuf',
};
/* 内容特征兜底识别 */
function guessLang(t) {
if (!t) return '';
if (/<\?php/i.test(t)) return 'php';
if (/^#!.*\b(?:bash|sh|zsh)\b/m.test(t)) return 'bash';
if (/^#!.*\bpython/m.test(t)) return 'python';
if (/^\s*|^\s*(?:const|let|var)\s+[\w$]+\s*=/m.test(t)) return 'javascript';
return '';
}
function detectLang(el) {
var i, c, cands = [];
if (el.querySelector) {
var cc = el.querySelector('code');
if (cc) cands.push(cc);
}
cands.push(el);
for (i = 0; i < cands.length; i++) {
c = cands[i];
var s = String(c.className || '') + ' ' + String(c.getAttribute('data-lang') || '') + ' ' +
String(c.getAttribute('data-language') || '') + ' ' + String(c.getAttribute('lang') || '');
var m = /(?:language|lang|brush|highlight|prettify)[-_: ]+([a-z0-9+#]+)/i.exec(s);
if (m) {
var v = LANG_ALIAS[m[1].toLowerCase()];
if (v) return v;
}
/* class 直接就是语言名,如 class="python" */
var cls = String(c.className || '').split(/\s+/);
for (var k = 0; k < cls.length; k++) {
var w = cls[k].toLowerCase().replace(/^(?:language|lang|brush|highlight|hljs|prism|prettyprint|source)[-:]/, '');
if (w.length > 1 && LANG_ALIAS[w]) return LANG_ALIAS[w];
}
}
/* 父级 data-lang */
var p = el.parentElement;
for (i = 0; i < 3 && p; i++, p = p.parentElement) {
if (!p.getAttribute) continue;
var dl = p.getAttribute('data-lang') || p.getAttribute('data-language');
if (dl) {
var v2 = LANG_ALIAS[String(dl).toLowerCase()];
if (v2) return v2;
}
}
return guessLang(String(el.textContent || '').slice(0, 4000));
}
/* 扫描页面代码块:祖先已收录的跳过,避免 pre > code 重复 */
function collectCode() {
var sel = 'pre, .highlight, .codehilite, [class*="language-"], [class*="highlight-"], [class*="brush:"]';
var found = [];
try { found = Array.prototype.slice.call(document.querySelectorAll(sel)); } catch (e) { return []; }
if (found.length > 400) found = found.slice(0, 400);
var out = [], kept = [], seen = {}, i;
function insideKept(el) {
var p = el.parentElement;
while (p) {
if (kept.indexOf(p) >= 0) return true;
p = p.parentElement;
}
return false;
}
for (i = 0; i < found.length; i++) {
var el = found[i];
if (el.closest && el.closest('#copyfree-host')) continue;
/* div.highlight > pre > code 这种,收敛到真正的 pre,语言信息仍从外层取 */
var target = el;
if (el.tagName !== 'PRE') {
var ps = el.querySelectorAll('pre');
if (ps.length === 1) target = ps[0];
else if (ps.length > 1) continue; /* 一整页都被包进来,跳过 */
}
if (insideKept(target)) continue;
var codeEl = target.querySelector('code') || target;
var text = String(codeEl.textContent || '').replace(/\r\n?/g, '\n').replace(/^\n+/, '').replace(/\n+$/, '');
if (text.trim().length < 8) continue;
if (text.length > 200000) continue; /* 超长多半是误判 */
var h = text.length + ':' + text.slice(0, 32) + text.slice(-32);
if (seen[h]) continue;
seen[h] = 1;
kept.push(target);
var lang = '';
try { lang = detectLang(el) || detectLang(target); } catch (e2) { lang = ''; }
out.push({ el: target, lang: lang, code: text, lines: text ? text.split('\n').length : 0 });
}
return out;
}
function codePanel() {
var old = document.getElementById('cf-code');
if (old) { old.remove(); return; }
var list = collectCode();
if (!list.length) { toast('本页没找到代码块'); return; }
var box = document.createElement('div');
box.id = 'cf-code';
box.style.cssText = 'position:fixed;inset:5% 7%;z-index:2147483003;background:#fff;border-radius:16px;' +
'box-shadow:0 20px 60px rgba(0,0,0,.35);display:flex;flex-direction:column;overflow:hidden;' +
'font:13px/1.6 -apple-system,"Segoe UI",sans-serif;color:#1c1c1e';
box.innerHTML =
'' +
'代码块提取' +
'共 ' + list.length + ' 块' +
'' +
'' +
'' +
'
';
var wrap = box.querySelector('#cf-clist');
list.forEach(function (it, i) {
var row = document.createElement('div');
row.style.cssText = 'border:.5px solid #e5e5ea;border-radius:10px;padding:9px 11px;margin-bottom:8px;background:#fafafa';
var top = document.createElement('div');
top.style.cssText = 'display:flex;align-items:center;gap:8px;margin-bottom:5px';
var idxEl = document.createElement('b');
idxEl.textContent = '#' + (i + 1);
idxEl.style.cssText = 'font-size:12px;color:#0a84ff';
var langEl = document.createElement('span');
langEl.textContent = it.lang || '未标注';
langEl.style.cssText = 'font-size:11px;padding:1px 7px;border-radius:99px;background:' +
(it.lang ? '#e8f8ec;color:#1a9e46' : '#eee;color:#8e8e93');
var linesEl = document.createElement('span');
linesEl.textContent = it.lines + ' 行 · ' + it.code.length + ' 字符';
linesEl.style.cssText = 'font-size:11px;color:#8e8e93';
var sp = document.createElement('span');
sp.style.cssText = 'flex:1';
var btn = document.createElement('button');
btn.textContent = '复制这块';
btn.style.cssText = 'border:none;background:#f2f2f7;border-radius:7px;padding:4px 10px;cursor:pointer;font-size:12px';
btn.onclick = function () {
var t = '```' + (it.lang || '') + '\n' + it.code + '\n```';
if (copyText(t)) toast('已复制第 ' + (i + 1) + ' 块');
else toast('复制失败');
};
top.appendChild(idxEl);
top.appendChild(langEl);
top.appendChild(linesEl);
top.appendChild(sp);
top.appendChild(btn);
var prev = document.createElement('div');
var one = it.code.replace(/\s+/g, ' ').trim();
prev.textContent = one.length > 78 ? one.slice(0, 78) + '…' : one;
prev.style.cssText = 'font:11.5px/1.5 ui-monospace,Consolas,monospace;color:#6b6b70;' +
'white-space:nowrap;overflow:hidden;text-overflow:ellipsis';
row.appendChild(top);
row.appendChild(prev);
wrap.appendChild(row);
});
box.querySelector('#cf-call').onclick = function () {
var txt = list.map(function (it) {
return '```' + (it.lang || '') + '\n' + it.code + '\n```';
}).join('\n\n');
if (copyText(txt)) toast('已复制 ' + list.length + ' 块 · ' + txt.length + ' 字');
else toast('复制失败');
};
box.querySelector('#cf-cx').onclick = function () { box.remove(); };
document.body.appendChild(box);
}
/* ---------- 面板 ---------- */
var host = null, root = null, dot = null, tip = null;
var CSS = [
'.dot{position:fixed;right:14px;bottom:56px;width:38px;height:38px;border-radius:50%;',
'background:linear-gradient(145deg,#34c759,#28a745);color:#fff;border:none;cursor:pointer;',
'font:600 13px/1 -apple-system,"Segoe UI",sans-serif;z-index:2147483000;',
'box-shadow:0 8px 20px rgba(52,199,89,.4);display:flex;align-items:center;justify-content:center}',
'.dot.off{background:linear-gradient(145deg,#8e8e93,#6c6c70);box-shadow:0 8px 20px rgba(0,0,0,.2)}',
'.card{position:fixed;right:14px;bottom:102px;width:252px;z-index:2147483001;',
'background:rgba(255,255,255,.97);border:.5px solid rgba(0,0,0,.1);border-radius:14px;',
'padding:12px 14px;font:13px/1.7 -apple-system,"Segoe UI",sans-serif;color:#1c1c1e;',
'box-shadow:0 12px 34px rgba(0,0,0,.22);display:none}',
'.card h4{margin:0 0 8px;font-size:13px;display:flex;align-items:center;gap:6px}',
'.card h4 i{font-style:normal;font-weight:400;font-size:10.5px;color:#8e8e93}',
'.row{display:flex;justify-content:space-between;color:#8e8e93;font-size:11.5px;margin-bottom:6px}',
'.row b{color:#1c1c1e}',
'.sw{display:flex;align-items:center;justify-content:space-between;margin:10px 0 4px;font-size:12.5px}',
'.sw.tight{margin:6px 0 0}',
'.hr{height:.5px;background:#eee;margin:9px 0 7px}',
'.tg{width:44px;height:24px;border-radius:99px;background:#e5e5ea;position:relative;cursor:pointer;transition:.2s}',
'.tg.on{background:#34c759}',
'.tg i{position:absolute;left:2px;top:2px;width:20px;height:20px;border-radius:50%;background:#fff;transition:.2s}',
'.tg.on i{left:22px}',
'.hint{color:#8e8e93;font-size:11px;margin-top:8px;line-height:1.65}',
'.b{border:none;border-radius:8px;padding:5px 11px;cursor:pointer;color:#1c1c1e;',
'font:600 12px/1.4 -apple-system,"Segoe UI",sans-serif;background:#f2f2f7}',
'.b.g{background:#34c759;color:#fff}.b.o{background:#ff9f0a;color:#fff}.b.l{background:#0a84ff;color:#fff}',
].join('');
function toast(t) {
if (tip) { tip.textContent = t; tip.style.opacity = '1'; return; }
tip = document.createElement('div');
tip.textContent = t;
tip.style.cssText = 'position:fixed;left:50%;top:18px;transform:translateX(-50%);z-index:2147483002;' +
'background:rgba(28,28,30,.92);color:#fff;padding:8px 16px;border-radius:99px;' +
'font:600 12.5px/1.4 -apple-system,sans-serif;transition:opacity .3s';
document.body.appendChild(tip);
setTimeout(function () { if (tip) { tip.style.opacity = '0'; setTimeout(function () { if (tip) { tip.remove(); tip = null; } }, 400); } }, 1400);
}
function render() {
if (!dot) return;
dot.classList.toggle('off', !S.on);
dot.title = S.on ? '复制解锁:已开启(点击设置)' : '复制解锁:已关闭';
try {
if (root) {
root.getElementById('st').textContent = S.on ? '已开启' : '已关闭';
var sw = root.getElementById('sw');
if (sw) sw.classList.toggle('on', S.on);
root.getElementById('a1').textContent = S.removedAttrs;
root.getElementById('a2').textContent = S.removedClasses;
root.getElementById('a3').textContent = S.blockedCalls || 0;
}
} catch (e) {}
}
function build() {
if (!document.body || document.getElementById('copyfree-host')) return;
host = document.createElement('div');
host.id = 'copyfree-host';
root = host.attachShadow({ mode: 'open' });
var st = document.createElement('style');
st.textContent = CSS;
root.appendChild(st);
dot = document.createElement('button');
dot.className = 'dot';
dot.textContent = '解开';
root.appendChild(dot);
var card = document.createElement('div');
card.className = 'card';
card.innerHTML =
'网页复制解锁 v' + VER + '
' +
'状态已开启
' +
'' +
'清理内联事件0
' +
'清理禁选样式0
' +
'拦截 preventDefault0
' +
'' +
'选中转 MD
' +
'整页转 MD
' +
'代码块提取
' +
'正文提取复制
' +
'表格导出
' +
'图片原图下载
' +
'Alt + C 强制复制选中
Alt + M 选中转 Markdown
' +
'Alt + Shift + K 代码块面板
Alt + Shift + C 复制全文
Alt + Shift + I 图片面板
';
root.appendChild(card);
document.body.appendChild(host);
dot.onclick = function () {
card.style.display = card.style.display === 'block' ? 'none' : 'block';
};
var imgBtn = root.getElementById('imgbtn');
if (imgBtn) imgBtn.onclick = function () { imgPanel(); };
var artBtn = root.getElementById('artbtn');
if (artBtn) artBtn.onclick = function () { articlePanel(); };
var codeBtn = root.getElementById('codebtn');
if (codeBtn) codeBtn.onclick = function () { codePanel(); };
var selMd = root.getElementById('selmd');
if (selMd) selMd.onclick = function () { copySelectionMd(); };
var pageMd = root.getElementById('pagemd');
if (pageMd) pageMd.onclick = function () { pageMdPanel(); };
var csvBtn = root.getElementById('csvbtn');
if (csvBtn) csvBtn.onclick = function () {
markTables();
var n = document.querySelectorAll('table[data-cf-mark="1"]').length;
toast(n ? '已标记 ' + n + ' 个表格,点角标导出' : '本页没找到可导出的表格');
};
var sw = root.getElementById('sw');
sw.onclick = function () {
S.on = !S.on;
try { localStorage.setItem(KEY, S.on ? '1' : '0'); } catch (e) {}
applyStyle();
render();
};
render();
}
function boot() {
applyStyle();
try { setTimeout(markTables, 1200); setInterval(markTables, 4000); } catch (e) {}
stripInline(document);
stripClasses(document);
build();
/* 动态内容:每 2 秒补扫一次(低成本) */
setInterval(function () {
if (!S.on) return;
stripClasses(document);
}, 2000);
window.addEventListener('load', function () { stripInline(document); stripClasses(document); });
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', boot);
} else {
boot();
}
document.addEventListener('keydown', function (e) {
if (e.altKey && e.shiftKey && (e.key === 'C' || e.key === 'c' || e.code === 'KeyC')) {
e.preventDefault();
try { copyArticle(); } catch (err) {}
}
if (e.altKey && e.shiftKey && (e.key === 'I' || e.key === 'i' || e.code === 'KeyI')) {
e.preventDefault();
try { imgPanel(); } catch (err) {}
}
if (e.altKey && e.shiftKey && (e.key === 'K' || e.key === 'k' || e.code === 'KeyK')) {
e.preventDefault();
try { codePanel(); } catch (err) {}
}
if (e.altKey && !e.shiftKey && (e.key === 'm' || e.key === 'M' || e.code === 'KeyM')) {
e.preventDefault();
try { copySelectionMd(); } catch (err) {}
}
}, true);
window.__copyfree = {
state: S, forceCopy: forceCopy, imgPanel: imgPanel, collectImages: collectImages, origUrl: origUrl,
articlePanel: articlePanel, copyArticle: copyArticle, exportTable: exportTable, markTables: markTables,
/* v1.3.0 新增 */
mdFromSelection: mdFromSelection, copySelectionMd: copySelectionMd, pageMarkdown: pageMarkdown,
pageMdPanel: pageMdPanel, collectCode: collectCode, codePanel: codePanel,
tableGrid: tableGrid, exportTableAs: exportTableAs, detectLang: detectLang,
};
})();