1+ /* global document */
2+
13const puppeteer = require ( 'puppeteer' )
4+ const crypto = require ( 'crypto' )
5+
6+ function hashString ( str ) {
7+ return crypto . createHash ( 'md5' ) . update ( str , 'utf8' ) . digest ( 'hex' )
8+ }
29
310function InvalidUrlError ( { url, statusCode, statusText} ) {
411 this . name = 'InvalidUrlError'
@@ -44,7 +51,6 @@ module.exports = async (url, {waitUntil = 'networkidle0'} = {}) => {
4451 // This is primarily for CSS-in-JS solutions
4552 // See: https://developer.mozilla.org/en-US/docs/Web/API/CSSRule/cssText
4653 const styleSheetsApiCss = await page . evaluate ( ( ) => {
47- /* global document */
4854 return [ ...document . styleSheets ]
4955 . filter ( stylesheet => stylesheet . href === null )
5056 . map ( stylesheet =>
@@ -55,6 +61,33 @@ module.exports = async (url, {waitUntil = 'networkidle0'} = {}) => {
5561 . join ( '\n' )
5662 } )
5763
64+ // Get all inline styles: <element style="">
65+ // This creates a new CSSRule for every inline style
66+ // attribute it encounters.
67+ //
68+ // Example:
69+ //
70+ // HTML:
71+ // <h1 style="color: red;">Text</h1>
72+ //
73+ // CSSRule:
74+ // [x-inline-style-237a7d] { color: red; }
75+ // ^^^^^^
76+ //
77+ // The 6-digit hash is based on the actual CSS, so it's not
78+ // necessarily unique!
79+ const inlineCssRules = await page . evaluate ( ( ) => {
80+ return [ ...document . querySelectorAll ( '[style]' ) ]
81+ . map ( element => element . getAttribute ( 'style' ) )
82+ . filter ( Boolean )
83+ } )
84+ const inlineCss = inlineCssRules
85+ . map ( rule => {
86+ const hash = hashString ( rule ) . slice ( - 6 )
87+ return `[x-inline-style-${ hash } ] { ${ rule } }`
88+ } )
89+ . join ( '\n' )
90+
5891 await browser . close ( )
5992
6093 // Turn the coverage Array into a single string of CSS
@@ -68,7 +101,7 @@ module.exports = async (url, {waitUntil = 'networkidle0'} = {}) => {
68101 . map ( ( { text} ) => text )
69102 . join ( '\n' )
70103
71- const css = [ styleSheetsApiCss , coverageCss ]
104+ const css = [ styleSheetsApiCss , coverageCss , inlineCss ]
72105 . filter ( Boolean )
73106 . join ( '\n' )
74107
0 commit comments