Greasemonkey script to override the font on Gitlab

This GreaseMonkey script overrides the font for code blocks on Gitlab. It can easily be applies to self-hosted instances by adding more @match specifiers.

See also:

The font set can be customised by changing the FONT constant

// ==UserScript==
// @name         GitLab code block font override
// @namespace    https://mafoo.org.uk/
// @author       foo@mafoo.org.uk
// @version      1.0
// @description  Override GitLab code block font with a configurable font
// @match        https://gitlab.com/*
// @grant        GM.setValue
// @grant        GM.getValue
// ==/UserScript==

(() => {
  'use strict';

  const FONT = 'Maple Mono, Fira Code, Noto Mono, Cascadia Code, Consolas, Menlo, Monaco, monospace';
  const ELEMENT_SELECTOR = "gitlab-font-override-style";

  function getFont() {
    return FONT;
  }

  function setFont(value) {
    GM.setValue(KEY, value);
    location.reload();
  }

  function injectStyle() {
    const existing = document.getElementById(ELEMENT_SELECTOR);
    if (existing) existing.remove();

    const style = document.createElement('style');
    style.id = ELEMENT_SELECTOR;
    style.textContent = `
      :root {
        --${ELEMENT_SELECTOR}: ${getFont()};
      }

      pre, code, kbd, samp,
      .code,
      .gl-code-block,
      .blob-content[data-blob-id] pre,
      .markdown code,
      .markdown pre,
      .wiki code,
      .wiki pre {
        font-family: var(--${ELEMENT_SELECTOR}) !important;
      }
    `;
    document.head.appendChild(style);
  }

  injectStyle();

  const observer = new MutationObserver(() => {
    if (!document.getElementById(ELEMENT_SELECTOR)) injectStyle();
  });

  observer.observe(document.documentElement, { childList: true, subtree: true });
})();