OpenAI-ChatGPT LaTeX Auto Render (with MathJax V2)

自动渲染 OpenAI 的 ChatGPT 页面上的 LaTeX 数学公式。

当前为 2022-12-07 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name OpenAI-ChatGPT LaTeX Auto Render (with MathJax V2)
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2.2
  5. // @author Scruel (https://github.com/scruel)
  6. // @description Auto typeset LaTeX math formulas on OpenAI ChatGPT page.
  7. // @description:zh-CN 自动渲染 OpenAI 的 ChatGPT 页面上的 LaTeX 数学公式。
  8. // @match https://chat.openai.com/chat
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. 'use strict';
  13.  
  14. async function addScript(url) {
  15. const scriptElement = document.createElement('script');
  16. scriptElement.src = url;
  17. scriptElement.async = true;
  18.  
  19. const headElement = document.getElementsByTagName('head')[0] || document.documentElement;
  20. headElement.insertBefore(scriptElement , headElement.firstChild);
  21. await waitScriptLoaded();
  22. }
  23.  
  24. function waitScriptLoaded() {
  25. return new Promise(async (resolve, reject) => {
  26. const resolver = () => {
  27. if (MathJax.hasOwnProperty('Hub')) {
  28. resolve();
  29. return;
  30. }
  31. // console.log("Loading...")
  32. window.setTimeout(resolver, 200);
  33. }
  34. resolver();
  35. });
  36. }
  37.  
  38. function renderTrigger() {
  39. setTimeout(renderLatex, window.renderDelay);
  40. }
  41.  
  42. function renderLatex() {
  43. const submitButton = document.querySelector('main form textarea+button');
  44. // console.log(submitButton)
  45. if (submitButton && !submitButton.disabled) {
  46. // console.log("Rendering...")
  47. MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
  48. }
  49. renderTrigger();
  50. }
  51.  
  52. (async function() {
  53. window.MathJax = {
  54. tex2jax: {
  55. inlineMath: [['$', '$']],
  56. displayMath : [['$$', '$$']]
  57. },
  58. CommonHTML: { linebreaks: { automatic: true } },
  59. "HTML-CSS": { linebreaks: { automatic: true } },
  60. SVG: { linebreaks: { automatic: true } }
  61. };
  62. await addScript('https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=TeX-AMS_CHTML');
  63.  
  64. window.renderDelay = 1000;
  65. renderTrigger();
  66. })();