ES2015方式。
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())
}
當在計算器上運行此,將返回["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"]
'TypeError:無法讀取未定義的屬性'nodeName'(google-chrome linux) – g33kz0r 2013-03-12 16:34:53