Auto LaTeX Renderer

Converts LaTeX on web pages into formatted math using MathJax

目前为 2024-11-06 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Auto LaTeX Renderer
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.5
  5. // @description Converts LaTeX on web pages into formatted math using MathJax
  6. // @match *://*/*
  7. // @grant none
  8. // ==/UserScript==
  9.  
  10. (function() {
  11. 'use strict';
  12.  
  13. // Set MathJax configuration to enable single dollar signs
  14. window.MathJax = {
  15. tex: {
  16. inlineMath: [['$', '$'], ['\\(', '\\)']],
  17. displayMath: [['$$', '$$'], ['\\[', '\\]']],
  18. processEscapes: true, // Allows \$ to escape dollar signs
  19. },
  20. options: {
  21. skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
  22. },
  23. };
  24.  
  25. // Function to add MathJax to the page
  26. function addMathJax(callback) {
  27. if (!window.MathJax || !window.MathJax.version) {
  28. let script = document.createElement('script');
  29. script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
  30. script.async = true;
  31. script.onload = function() {
  32. console.log('MathJax loaded');
  33. if (callback) callback();
  34. };
  35. script.onerror = function() {
  36. console.error('Failed to load MathJax. Please check your network or CDN availability.');
  37. // Retry in case of failure
  38. setTimeout(function(){ addMathJax(callback); }, 2000);
  39. };
  40. document.head.appendChild(script);
  41. } else {
  42. if (callback) callback();
  43. }
  44. }
  45.  
  46. // Function to scan the document and render LaTeX
  47. function renderLatex() {
  48. try {
  49. if (window.MathJax && MathJax.typesetPromise) {
  50. MathJax.typesetPromise().catch(function (err) {
  51. console.error('MathJax typeset failed:', err);
  52. });
  53. } else {
  54. console.log('MathJax not loaded yet. Retrying in 500ms...');
  55. setTimeout(renderLatex, 500);
  56. }
  57. } catch (error) {
  58. console.error('Error during LaTeX rendering:', error);
  59. }
  60. }
  61.  
  62. // Initial injection after page fully loads
  63. window.addEventListener('load', function() {
  64. addMathJax(function() {
  65. // Initial render for existing content
  66. renderLatex();
  67.  
  68. // Observe the DOM for changes and render LaTeX
  69. const observer = new MutationObserver(() => {
  70. // Throttle the renderLatex calls
  71. if (observer.renderTimeout) clearTimeout(observer.renderTimeout);
  72. observer.renderTimeout = setTimeout(renderLatex, 300);
  73. });
  74.  
  75. observer.observe(document.body, { childList: true, subtree: true, characterData: true });
  76. });
  77. });
  78.  
  79. })();