Skip to content

Instantly share code, notes, and snippets.

@gorshkov-leonid
Last active August 19, 2025 11:18
Show Gist options
  • Save gorshkov-leonid/082105cf462bb99614d670041501d7d5 to your computer and use it in GitHub Desktop.
Save gorshkov-leonid/082105cf462bb99614d670041501d7d5 to your computer and use it in GitHub Desktop.
Print Font Using Puppeteer
       async function printFont(index: number): Promise<boolean> {
            const res = await cdp.send(
                "Runtime.evaluate",
                {expression: `Array.from(document?.querySelector('#my-iframe')?.contentWindow?.document?.body?.querySelector('#my-webcomponent')?.shadowRoot?.querySelectorAll('text') || []).filter((c) => c.textContent && (c.textContent.includes('Access') || c.textContent.includes('TV')))[${index}]`},
            ) as any
            if (res?.result?.objectId) {
                // eslint-disable-next-line prefer-destructuring
                const nodeId = ((await cdp.send("DOM.requestNode", {objectId: res.result.objectId})) as any).nodeId
                if (nodeId) {
                    // eslint-disable-next-line prefer-destructuring
                    const outerHTML = ((await cdp.send("DOM.getOuterHTML", {nodeId: nodeId})) as any).outerHTML
                    let text = ""
                    if (outerHTML) {
                        const parts = outerHTML.match(/>(.*)<\/text>/)
                        if (parts.length >= 2) {
                            // eslint-disable-next-line prefer-destructuring
                            text = parts[1]
                        }
                    }
                    const fonts = await cdp.send("CSS.getPlatformFontsForNode", {nodeId: nodeId})
                    cons.log("!!!!!!!!!!!!!!!! fonts", text, JSON.stringify(fonts))
                    return true
                }
            }
            return false            
        }
  
        const cdp = await page.target().createCDPSession()
        try {
            await cdp.send("Runtime.enable")
            await cdp.send("DOM.enable")
            await cdp.send("CSS.enable")
            // https://github.com/puppeteer/puppeteer/issues/9077 https://bugs.chromium.org/p/chromium/issues/detail?id=1374241
            await cdp.send("DOM.getDocument", {depth: 0})
            for (let i = 0, res = true; res; i++) {
                res = await printFont(i)
            }
        }
        finally {
            await cdp.detach()
        }

See

https://stackoverflow.com/questions/47911613/fetch-rendered-font-using-chrome-headless-browser/47914111#47914111

https://stackoverflow.com/questions/56226426/nodeid-to-element-handle

puppeteer/puppeteer#384

https://stackoverflow.com/questions/55835999/how-to-go-from-elementhandle-to-dom-element

puppeteer/puppeteer#9284

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment