Script to find all fonts used on a page

后端 未结 6 1251
無奈伤痛
無奈伤痛 2020-12-10 04:42

Is there easy way to parse a HTML page to find all the fonts used (or all the font stacks used)?

Or similarly, is there a script that parses a page and returns which

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 05:15

    ES2015 way of doing it, also supporting ::before and ::after pseudo-selectors.

    function listFonts () {
    
      let fonts = []
    
      for (let node of document.querySelectorAll('*')) {
    
        if (!node.style) continue
    
        for (let pseudo of ['', ':before', ':after']) {
    
          let fontFamily = getComputedStyle(node, pseudo).fontFamily
    
          fonts = fonts.concat(fontFamily.split(/\n*,\n*/g))
    
        }
    
      }
    
      // Remove duplicate elements from fonts array
      // and remove the surrounding quotes around elements
      return [...new Set(fonts)]
        .map(font => font.replace(/^\s*['"]([^'"]*)['"]\s*$/, '$1').trim())
    
    }
    

    When running this on StackOverflow, will return ["Times", "Arial", "Helvetica Neue", "Helvetica", "sans-serif", "BlinkMacSystemFont", "Consolas", "Menlo", "Monaco", "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", "monospace"]

提交回复
热议问题