anurag
anurag

Reputation: 630

How to get all fonts with style using puppeteer

I am using puppeteer to get list of fonts that for a given webpage.

Tried the following snippet to get all fonts for a given page.

const selector = 'html';
const getFontProperty = async (page) => {
  const font = await page.evaluate((selector) => {
    let elements = Array.from(document.querySelectorAll(selector));
    console.log(elements)
    let links = elements.map(element => {
      console.log(element)
      console.log(getComputedStyle(element).font)
    });
  }, selector);
  return font;
}

However, elements comes out as undefined.

[ref link: puppeteer page.evaluate querySelectorAll return empty objects

Upvotes: 0

Views: 2705

Answers (1)

Vaviloff
Vaviloff

Reputation: 16856

It happens because you don't actually return font definitions, but console.log them. If you don't use a short form of arrow function, you need to explicitly return a value:

let links = elements.map(element => {
  console.log(element)
  return getComputedStyle(element).font
});

Otherwise you can just write:

let links = elems.map(element => getComputedStyle(element).font);

Update: You also must return data you're seeking from page.evaluate:

const font = await page.evaluate(selector => {

    let elements = Array.from(document.querySelectorAll(selector));
    let links = elems.map(element => getComputedStyle(element).font);

    return links; // <-- return data from page.evaluate

}, selector);

Upvotes: 1

Related Questions