I'm currently working on a chrome extension that will allow me to extract font files from fonts on a webpage.
However, I'm noticing that for some websites (like Ahrefs) certain fonts are applied to elements that are not visible on the page.
For example if I check window.getComputedStyle().fontFamily for the <title> tag, I see the font as Times.
Since this is the title tag, there are no elements with that font actually being displayed on the page. Is it possible to only filter for nodes that have text that is visible on the webpage?
Note: The nodes don't have to be only visible in the viewport. I' like to pickup nodes that are anywhere on the page.
Thanks!
Your best best might be to use querySelectorAll to get all child elements within body. Wrapping the querySelectorAll with [].slide.call to cleanly turn the NodeList into an Array, allowing for us to filter with [].filter.
var childNodes = [].slice.call(document.body.querySelectorAll("*"));
var visibleNodes = childNodes.filter(node => node.offsetWidth > 0 && node.offsetHeight > 0);
For most cases, checking for visibility is of an element is preferred using an elements offsetWidth and offsetHeight attributes as compared to jQuery’s naive method of the :visible selector where it just checks if a CSS attribute display: none exists.
If you also want a list of all computed font families for visible elements you can use the same window.getComputedStyle to get the used value and filter out all empty or null values with double bangs !!.
var fontFamilies = visibleNodes.map(node => window.getComputedStyle(node).fontFamily).filter(ff => !!ff));
Using a unique List of font families using the … spread operator in-combo with Set.
var uniqueFamilies = […new Set(fontFamilies)];