Greasy Fork

Greasy Fork is available in English.

网页转为Markdown

将当前页面的HTML转换为Markdown。

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         网页转为Markdown
// @namespace    https://ez118.github.io/
// @version      0.2
// @description  将当前页面的HTML转换为Markdown。
// @author       ZZY_WISU
// @match        *://*/*
// @connect      *
// @license      GNU GPLv3
// @icon         https://markdown.com.cn/hero.png
// @run-at       context-menu
// @grant        GM_setClipboard
// @require      https://unpkg.com/[email protected]/dist/turndown.js
// ==/UserScript==

/* =====[ 用户配置 ]===== */

const isConvertToAbsoluteUrls = true; // 是否自动将相对链接转为绝对链接(true:是 / false:否)

/* ====================== */



function copy2clipboard(txt) {
    GM_setClipboard(txt);
}

function convertRelativeUrlsToAbsolute(markdown, baseUrl) {
    // 创建一个a元素用来解析URL
    const parser = document.createElement('a');
    parser.href = baseUrl;

    // 提取baseUrl的协议和主机部分
    const baseOrigin = `${parser.protocol}//${parser.host}`;

    // 提取baseUrl的路径部分
    const basePath = parser.pathname.substring(0, parser.pathname.lastIndexOf('/'));

    // 正则表达式匹配Markdown中的链接和图片
    const regex = /(!?\[.*?\]\()([^)]+)(\))/g;

    // 回调函数处理匹配的链接或图片路径
    return markdown.replace(regex, (match, prefix, url, suffix) => {
        // 忽略已是绝对链接的URL
        if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('//')) {
            return match;
        }

        // 拼接相对路径为绝对路径
        let absoluteUrl;
        if (url.startsWith('/')) {
            absoluteUrl = baseOrigin + url;
        } else {
            absoluteUrl = baseOrigin + basePath + '/' + url;
        }

        return `${prefix}${absoluteUrl}${suffix}`;
    });
}

function getWebContents(txt) {
    /* 去掉影响转换的标签 */
    var markdown = txt.replace(/<script.*?>.*?<\/script>/gis, "")
        .replace(/<style.*?>.*?<\/style>/gis, "")
        .replace(/<nav.*?>.*?<\/nav>/gis, "");


    /* html转markdown */
    const turndownService = new TurndownService();
    markdown = turndownService.turndown(markdown);

    return markdown;
}


(function () {
    'use strict';

    var md = getWebContents(document.body.innerHTML);

    if(isConvertToAbsoluteUrls){
        md = convertRelativeUrlsToAbsolute(md, window.location.href);
    }

    copy2clipboard(md);

    alert("已复制");
})();