自动渲染HTML嵌入的数学公式 (MathJax)

自动加载 MathJax 并渲染网页中的数学公式。

// ==UserScript==
// @name         自动渲染HTML嵌入的数学公式 (MathJax)
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  自动加载 MathJax 并渲染网页中的数学公式。
// @author       KiwiFruit
// @match        *://*/*
// @grant        none
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    // 检查是否已经加载了 MathJax
    if (typeof MathJax !== 'undefined') {
        console.log('MathJax 已经加载,跳过重复加载。');
        return;
    }

    // 配置 MathJax
    window.MathJax = {
        tex: {
            inlineMath: [['$', '$'], ['\$', '\$']], // 定义行内公式标识符
            displayMath: [['$$', '$$'], ['\$', '\$']] // 定义块级公式标识符
        },
        options: {
            skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre'], // 忽略这些标签的内容
            ignoreHtmlClass: 'tex2jax_ignore' // 忽略带有此类名的元素
        }
    };

    // 动态加载 MathJax
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
    script.async = true;
    script.onload = function () {
        console.log('MathJax 加载完成,开始渲染数学公式...');
        // 如果需要手动触发渲染,可以调用 MathJax.typesetPromise()
        if (typeof MathJax !== 'undefined') {
            MathJax.typesetPromise().catch(err => console.error('MathJax 渲染失败:', err));
        }
    };
    script.onerror = function () {
        console.error('MathJax 加载失败,请检查网络连接或 CDN 地址。');
    };

    // 将 MathJax 脚本插入到页面中
    document.head.appendChild(script);
})();