Font Substitution v3

Substitutes arbitrary fonts on webpages

  1. // ==UserScript==
  2. // @name Font Substitution v3
  3. // @description Substitutes arbitrary fonts on webpages
  4. // @author Alan Davies
  5. // @copyright 2015, Alan Davies
  6. // @version 3.0.2
  7. // @date 2015-08-26
  8. // @namespace FontSub3
  9. // @include *
  10. // @grant GM_addStyle
  11. // @run-at document-start
  12. // ==/UserScript==
  13.  
  14. var globalDebug = false;
  15.  
  16. if (globalDebug) console.log("Font substitution start");
  17.  
  18. var fontMap = new Map([
  19. [ "arial", "Verdana" ],
  20. [ "helvetica", "Verdana" ],
  21. [ "courier", "Consolas" ],
  22. [ "courier new", "Consolas" ]
  23. ]);
  24.  
  25. var weights = [ "normal" , "bold" ];
  26. var styles = [ "normal" , "italic" ];
  27.  
  28. function Capitalize(string)
  29. {
  30. return string.charAt(0).toUpperCase() + string.slice(1);
  31. }
  32.  
  33. function OverrideFontFaces()
  34. {
  35. for (let fontSub of fontMap)
  36. {
  37. for (w = 0; w < weights.length; ++w)
  38. {
  39. let weight = weights[w];
  40.  
  41. for (s = 0; s < styles.length; ++s)
  42. {
  43. let style = styles[s];
  44. let replacementFont = fontSub[1];
  45. if (weight != "normal")
  46. replacementFont = replacementFont + " " + Capitalize(weight);
  47.  
  48. if (style != "normal")
  49. replacementFont = replacementFont + " " + Capitalize(style);
  50.  
  51. let css =
  52. "@font-face {" +
  53. "font-family: \'" + fontSub[0] + "\'; " +
  54. "src: local(\'" + replacementFont + "\'); " +
  55. "font-weight: " + weight + "; " +
  56. "font-style: " + style + "; " +
  57. "}";
  58.  
  59. if (globalDebug) console.log("Adding CSS: " + css);
  60.  
  61. GM_addStyle(css);
  62. }
  63. }
  64. }
  65. }
  66.  
  67. var done = false;
  68.  
  69. // create an observer instance
  70. var observer = new MutationObserver(function(mutations) {
  71. if (globalDebug) console.log("Mutation event");
  72. // Add the font face overrides once we have a body element
  73. if (!done && (null != document.body))
  74. {
  75. observer.disconnect();
  76. OverrideFontFaces();
  77. done = true;
  78. }
  79. });
  80.  
  81. observer.observe(document, { childList: true, attributes: false, characterData: false, subtree: true });