← Pablo Murad

Snippets

Font Peek, a bookmarklet that shows the font a page really uses

Font Peek is a bookmarklet I wrote: hover any text on a page to see which font the browser is really drawing, then click for the full font stack, size, weight, color and every font the page uses.

CSS lets a site list several fonts for the same text, in order of preference, and the browser draws it with the first one it can find.1 The stylesheet says what the designer asked for. Font Peek shows what the browser actually used.

Run it and hover over any text: a small label follows the mouse with the font, the size and the weight. Click, and a panel pins the full picture:

  • the font being drawn, and whether it's a web font the page downloaded (with a link to the file) or one installed on the computer;
  • size, line height, weight, style, letter spacing and color;
  • the whole font stack, each entry marked as available or missing;
  • every font used on the page, and on how many elements.

Copy puts the report on the clipboard as plain text. Esc closes the panel, and so does running it again. The panel follows the system's dark mode.

There are two ways to run it:

  1. Paste the file into the developer console (F12, then Console) and press Enter.2
  2. Keep it as a bookmarklet.3 Create a new bookmark called Font Peek and, in the address field, type javascript: followed by the whole file. It only uses block comments and ends every statement with a semicolon, so it keeps working when the browser squeezes the lines into one.
font-peek.js raw
/*
  Font Peek
  by Pablo Murad · https://pablomurad.com

  Hover any text to see which font the browser is really drawing it with,
  out of the whole font stack. Click to pin a full report. Esc closes.
  Run it again to toggle.
*/
(() => {
  const ID = "font-peek-root";
  const old = document.getElementById(ID);
  if (old) { old.__close(); return; }

  const GENERIC = new Set([
    "serif", "sans-serif", "monospace", "cursive", "fantasy", "math",
    "system-ui", "ui-serif", "ui-sans-serif", "ui-monospace", "ui-rounded",
    "emoji", "fangsong", "-apple-system", "blinkmacsystemfont"
  ]);
  const PROBES = ["mmmmmmmmmmlli", "WQ@#0123456789", "abcdefghij ABCDEFGHIJ", "il1|.,;:!"];
  const BASES = ["monospace", "serif", "sans-serif"];

  /* Canvas text measuring: a font counts as installed if it changes the width
     of at least one probe string against at least one generic fallback. */
  const ctx = document.createElement("canvas").getContext("2d");
  const width = (font, text) => { ctx.font = font; return ctx.measureText(text).width; };
  const baseline = {};
  BASES.forEach(b => { baseline[b] = PROBES.map(p => width(`72px ${b}`, p)); });
  const installedCache = new Map();
  const isInstalled = family => {
    const key = family.toLowerCase();
    if (!installedCache.has(key)) {
      const q = `"${family.replace(/"/g, '\\"')}"`;
      installedCache.set(key, BASES.some(b =>
        PROBES.some((p, i) => width(`72px ${q}, ${b}`, p) !== baseline[b][i])));
    }
    return installedCache.get(key);
  };

  /* Web fonts the page has actually loaded, and where they came from. */
  const loaded = new Set();
  try {
    document.fonts.forEach(f => {
      if (f.status === "loaded") loaded.add(f.family.replace(/^["']|["']$/g, "").toLowerCase());
    });
  } catch (e) {}
  const sources = new Map();
  const readRules = rules => {
    for (const r of rules) {
      if (r.type === CSSRule.FONT_FACE_RULE) {
        const fam = (r.style.getPropertyValue("font-family") || "").replace(/^["']|["']$/g, "").trim().toLowerCase();
        const url = (r.style.getPropertyValue("src").match(/url\(["']?([^"')]+)/) || [])[1];
        if (fam && url && !sources.has(fam)) sources.set(fam, url);
      } else if (r.cssRules) {
        try { readRules(r.cssRules); } catch (e) {}
      }
    }
  };
  for (const sheet of document.styleSheets) {
    try { readRules(sheet.cssRules); } catch (e) {} /* cross-origin sheets can't be read */
  }

  const splitStack = stack => stack.split(",").map(s => s.trim().replace(/^["']|["']$/g, "")).filter(Boolean);

  const classify = family => {
    const key = family.toLowerCase();
    if (GENERIC.has(key)) return { family, kind: "generic", ok: true };
    if (loaded.has(key)) return { family, kind: "web font", ok: true, src: sources.get(key) };
    if (isInstalled(family)) return { family, kind: "installed", ok: true };
    return { family, kind: "missing", ok: false };
  };

  const toHex = rgb => {
    const m = rgb.match(/\d+(\.\d+)?/g);
    if (!m || m.length < 3) return rgb;
    const hex = "#" + m.slice(0, 3).map(n => (+n).toString(16).padStart(2, "0")).join("");
    return m[3] !== undefined && +m[3] < 1 ? `${hex} (${Math.round(m[3] * 100)}% opacity)` : hex;
  };

  const inspect = el => {
    const cs = getComputedStyle(el);
    const stack = splitStack(cs.fontFamily).map(classify);
    const used = stack.find(f => f.ok);
    return {
      el, stack, used: used ? used.family : "browser default",
      usedKind: used ? used.kind : "fallback",
      size: cs.fontSize, lineHeight: cs.lineHeight, weight: cs.fontWeight,
      style: cs.fontStyle, spacing: cs.letterSpacing, color: toHex(cs.color),
      features: cs.fontFeatureSettings !== "normal" ? cs.fontFeatureSettings : "",
      raw: cs.fontFamily
    };
  };

  /* Every font family the page renders text in, counted by element. */
  const pageFonts = () => {
    const counts = new Map();
    const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
    let n = 0, node;
    const seen = new Set();
    while ((node = walker.nextNode()) && n < 4000) {
      const el = node.parentElement;
      if (!el || seen.has(el) || !node.textContent.trim() || host.contains(el)) continue;
      seen.add(el); n++;
      const info = inspect(el);
      counts.set(info.used, (counts.get(info.used) || 0) + 1);
    }
    return [...counts.entries()].sort((a, b) => b[1] - a[1]);
  };

  const describe = el => {
    let s = el.tagName.toLowerCase();
    if (el.id) s += "#" + el.id;
    if (el.classList.length) s += "." + [...el.classList].slice(0, 2).join(".");
    return s;
  };

  /* The interface lives in a shadow root, so the page's CSS can't touch it. */
  const host = document.createElement("div");
  host.id = ID;
  Object.assign(host.style, { position: "fixed", inset: "0", zIndex: "2147483647", pointerEvents: "none" });
  const root = host.attachShadow({ mode: "open" });
  const css = `
    :host { all: initial; }
    * { box-sizing: border-box; }
    .box { position: fixed; border: 2px solid #4dabf7; background: rgba(77,171,247,.08); border-radius: 3px; pointer-events: none; display: none; }
    .tip { position: fixed; display: none; pointer-events: none; padding: 4px 8px; border-radius: 6px;
      font: 12px/1.4 ui-monospace, Menlo, Consolas, monospace; background: #1b1e22; color: #f1f3f5; white-space: nowrap; }
    .panel { position: fixed; right: 16px; bottom: 16px; width: min(380px, calc(100vw - 32px)); max-height: 70vh; overflow: auto;
      pointer-events: auto; padding: 14px 16px; border-radius: 12px; border: 1px solid #dee2e6;
      font: 13px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; color: #212529; background: #fff;
      box-shadow: 0 10px 30px rgba(0,0,0,.18); }
    @media (prefers-color-scheme: dark) { .panel { background: #1b1e22; color: #e9ecef; border-color: #343a40; } }
    .head { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 8px; }
    .title { font-weight: 700; font-size: 14px; }
    .hint { opacity: .65; font-size: 12px; }
    .big { font-size: 20px; font-weight: 700; margin: 6px 0 2px; word-break: break-word; }
    .kind { font-size: 12px; opacity: .7; margin-bottom: 10px; }
    table { width: 100%; border-collapse: collapse; margin: 6px 0 10px; }
    td { padding: 3px 0; vertical-align: top; }
    td:first-child { opacity: .65; width: 38%; }
    ul { list-style: none; margin: 4px 0 10px; padding: 0; }
    li { padding: 2px 0; font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; word-break: break-all; }
    .ok { color: #2b8a3e; } .no { color: #c92a2a; } .gen { color: #5f3dc4; }
    @media (prefers-color-scheme: dark) { .ok { color: #69db7c; } .no { color: #ff8787; } .gen { color: #b197fc; } }
    h3 { font-size: 12px; text-transform: uppercase; letter-spacing: .05em; opacity: .6; margin: 10px 0 2px; }
    button { font: inherit; font-size: 12px; padding: 4px 10px; border-radius: 6px; border: 1px solid #ced4da;
      background: transparent; color: inherit; cursor: pointer; }
    button:hover { border-color: #4dabf7; }
    .row { display: flex; gap: 6px; }
    a { color: #1c7ed6; word-break: break-all; }
    .by { margin-top: 10px; font-size: 11px; opacity: .55; }
    .by a { color: inherit; }
  `;
  try {
    const sheet = new CSSStyleSheet();
    sheet.replaceSync(css); /* works even on pages that block inline <style> */
    root.adoptedStyleSheets = [sheet];
  } catch (e) {
    const st = document.createElement("style");
    st.textContent = css;
    root.appendChild(st);
  }
  const box = document.createElement("div"); box.className = "box";
  const tip = document.createElement("div"); tip.className = "tip";
  const panel = document.createElement("div"); panel.className = "panel";
  root.append(box, tip, panel);
  document.documentElement.appendChild(host);

  const esc = s => String(s).replace(/[&<>"]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
  let lastReport = "";

  const showIntro = () => {
    panel.innerHTML = `<div class="head"><span class="title">Font Peek</span><button data-x>Close</button></div>
      <div class="hint">Hover any text to see its font. Click to pin the details. Esc closes.</div><div class="by">by <a href="https://pablomurad.com" target="_blank" rel="noopener">Pablo Murad</a></div>`;
  };

  const showReport = info => {
    const fonts = pageFonts();
    const mark = f => f.kind === "missing" ? `<span class="no">✗ ${esc(f.family)}</span> <span class="hint">not available</span>`
      : f.kind === "generic" ? `<span class="gen">◆ ${esc(f.family)}</span> <span class="hint">generic keyword</span>`
      : `<span class="ok">✓ ${esc(f.family)}</span> <span class="hint">${f.kind}</span>`;
    const src = info.stack.find(f => f.family === info.used && f.src);
    panel.innerHTML = `
      <div class="head"><span class="title">Font Peek</span>
        <span class="row"><button data-copy>Copy</button><button data-x>Close</button></span></div>
      <div class="hint">${esc(describe(info.el))}</div>
      <div class="big">${esc(info.used)}</div>
      <div class="kind">${esc(info.usedKind)}${src ? ` · <a href="${esc(src.src)}" target="_blank" rel="noopener">file</a>` : ""}</div>
      <table>
        <tr><td>Size</td><td>${esc(info.size)}</td></tr>
        <tr><td>Line height</td><td>${esc(info.lineHeight)}</td></tr>
        <tr><td>Weight</td><td>${esc(info.weight)}</td></tr>
        <tr><td>Style</td><td>${esc(info.style)}</td></tr>
        <tr><td>Letter spacing</td><td>${esc(info.spacing)}</td></tr>
        <tr><td>Color</td><td>${esc(info.color)}</td></tr>
        ${info.features ? `<tr><td>Features</td><td>${esc(info.features)}</td></tr>` : ""}
      </table>
      <h3>Font stack</h3>
      <ul>${info.stack.map(f => `<li>${mark(f)}</li>`).join("")}</ul>
      <h3>Fonts on this page</h3>
      <ul>${fonts.map(([f, c]) => `<li>${esc(f)} <span class="hint">· ${c} element${c > 1 ? "s" : ""}</span></li>`).join("")}</ul>
      <div class="hint">Click other text to inspect it.</div><div class="by">by <a href="https://pablomurad.com" target="_blank" rel="noopener">Pablo Murad</a></div>`;
    lastReport = [
      `Font Peek: ${location.href}`, `Element: ${describe(info.el)}`,
      `Rendered font: ${info.used} (${info.usedKind})`,
      `Size ${info.size}, line height ${info.lineHeight}, weight ${info.weight}, style ${info.style}, letter spacing ${info.spacing}, color ${info.color}`,
      `Stack: ${info.raw}`,
      ...info.stack.map(f => `  ${f.ok ? "+" : "-"} ${f.family} (${f.kind})`),
      "Fonts on this page:", ...fonts.map(([f, c]) => `  ${f}: ${c}`)
    ].join("\n");
  };

  const textTarget = e => {
    const el = document.elementFromPoint(e.clientX, e.clientY);
    return el && !host.contains(el) && el !== document.documentElement ? el : null;
  };

  const onMove = e => {
    const el = textTarget(e);
    if (!el) { box.style.display = tip.style.display = "none"; return; }
    const r = el.getBoundingClientRect();
    Object.assign(box.style, { display: "block", left: r.left + "px", top: r.top + "px", width: r.width + "px", height: r.height + "px" });
    const info = inspect(el);
    tip.textContent = `${info.used} · ${info.size} · ${info.weight}`;
    tip.style.display = "block";
    tip.style.left = Math.min(e.clientX + 12, innerWidth - tip.offsetWidth - 8) + "px";
    tip.style.top = Math.min(e.clientY + 16, innerHeight - 30) + "px";
  };

  const onClick = e => {
    if (e.composedPath().includes(host)) return;
    const el = textTarget(e);
    if (!el) return;
    e.preventDefault(); e.stopPropagation();
    showReport(inspect(el));
  };

  const onKey = e => { if (e.key === "Escape") close(); };

  panel.addEventListener("click", e => {
    if (e.target.closest("[data-x]")) close();
    if (e.target.closest("[data-copy]") && lastReport) {
      navigator.clipboard.writeText(lastReport).then(
        () => { e.target.textContent = "Copied"; },
        () => { e.target.textContent = "Copy failed"; });
    }
  });

  const close = () => {
    document.removeEventListener("mousemove", onMove, true);
    document.removeEventListener("click", onClick, true);
    document.removeEventListener("keydown", onKey, true);
    host.remove();
  };
  host.__close = close;

  document.addEventListener("mousemove", onMove, true);
  document.addEventListener("click", onClick, true);
  document.addEventListener("keydown", onKey, true);

  /* Text already selected? Start with a report on it. */
  const sel = getSelection();
  if (sel && sel.toString().trim() && sel.anchorNode) {
    const el = sel.anchorNode.nodeType === 1 ? sel.anchorNode : sel.anchorNode.parentElement;
    if (el) { showReport(inspect(el)); return; }
  }
  showIntro();
})();

curl -O https://pablomurad.com/snippets/font-peek.js

The Font Peek panel on pablomurad.com, open over the title of the MuradKey post. The element is h1.p-name.title-long and the rendered font is source-serif-4, a web font: 40px, line height 42px, weight 600, normal style, letter spacing -0.8px, color #111111. The font stack shows source-serif-4 as a web font, Georgia as not available, Times New Roman as installed and serif as a generic keyword. Fonts on this page: ibm-plex-mono on 177 elements, source-serif-4 on 135, Courier on 20, caveat on 12.
Font Peek pinned on the title of the MuradKey post.

On the title of my MuradKey post, the site asks for Source Serif 4 first and the browser has it as a web font, so the rest of the stack never comes into play.

For web fonts, the browser itself keeps a list of what the page downloaded. For everything else, the script measures a few strings of text on a canvas, once with only a generic family and once with the font in front of it. If the width changes, the font is installed.4

Notes

  1. That list is the font-family property. It usually ends with a generic family such as serif or sans-serif, which means "whatever this system uses for that", so there is always something left to draw with. ↩

  2. The first time, Chrome and Firefox may refuse the paste and ask for "allow pasting" to be typed. It's a guard against people being tricked into running code they don't understand, so it's worth reading any script before pasting it, this one included. ↩

  3. A bookmarklet is a bookmark whose address is JavaScript instead of a page. Steve Kangas coined the word in 1998, when he started collecting them on bookmarklets.com. ↩

  4. On Linux, fontconfig can answer a request for a missing font with a look-alike that has the same metrics, so a name like Times New Roman may show up as installed. That's what happened on the machine that took the screenshot above. ↩