Stackexchange TeX copy

Copy TeX code from stackexchange sites by clicking on equations

  1. // ==UserScript==
  2. // @name Stackexchange TeX copy
  3. // @namespace http://tampermonkey.net/
  4. // @version 2023-12-26
  5. // @description Copy TeX code from stackexchange sites by clicking on equations
  6. // @author joelsleeba
  7. // @match https://math.stackexchange.com
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=stackexchange.com
  9. // @license AGPL v3
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // Your code here...
  16. function handleEquationClick(event) {
  17. event.stopPropagation();
  18. const equation = event.target.closest(".math-container")
  19.  
  20. if (equation) {
  21. // Wikipedia nicely packs a single <math> element inside each .mwe-math-element classes
  22. const mathScript = equation.querySelector("script[type='math/tex']");
  23. const tex = mathScript.innerText
  24. console.log(tex);
  25.  
  26. // Do something with the joined alt text here, e.g., display it in an alert:
  27. navigator.clipboard.writeText(tex)
  28. .then(() => {
  29. // Copying succeeded
  30. console.log("TeX copied to clipboard");
  31. })
  32. .catch(err => {
  33. // Copying failed, handle the error
  34. console.error("Failed to copy TeX :", err);
  35. });
  36. } else {
  37. console.log("Clicked element is not within an .mwe-math-element");
  38. }
  39. }
  40.  
  41. // // Attach the event listener to all descendants of .ltx_Math which are not themselves descendants of .ltx_equation
  42. document.querySelectorAll(".math-container *").forEach(element => {
  43. element.addEventListener("click", handleEquationClick);
  44. });
  45.  
  46. })();