Created
March 30, 2019 23:13
-
-
Save superfein/e6c2c7a8848fa4aa81eef41cb1be1278 to your computer and use it in GitHub Desktop.
Uses the Puppeteer node module to extract the coverage CSS from Chrome, for a specific URL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const puppeteer = require('puppeteer'); | |
// Include to be able to export files with node | |
const fs = require('fs'); | |
// This prepares the filenames for the coverage .css files | |
function exportCSSFileName(url) { | |
// Remove https:// from the beginning of the string | |
// Remove .css* from the end of the string | |
var newFileName = url.substring(8, url.search("\\.css")); | |
// Replace all forward slashes with hyphens | |
newFileName = newFileName.replace(/\//g, "-"); | |
// Return filename with .css concatenated at the end | |
return newFileName+".css"; | |
} | |
(async () => { | |
const browser = await puppeteer.launch(); | |
const page = await browser.newPage(); | |
// Begin collecting CSS coverage data | |
await Promise.all([ | |
page.coverage.startCSSCoverage() | |
]); | |
// Extract coverage CSS from this URL | |
await page.goto('https://google.com'); | |
// Stop collection and retrieve the coverage iterator | |
const cssCoverage = await Promise.all([ | |
page.coverage.stopCSSCoverage(), | |
]); | |
// Investigate CSS Coverage and Extract Used CSS | |
const css_coverage = [...cssCoverage]; | |
for (const entry of css_coverage[0]) { | |
// Check if the css asset contains '.css' in the URL, if it does then export the coverage CSS | |
// Useful for filtering out inline styles in the web page | |
if ( entry.url.search("\\.css") !== -1 ) { | |
// Init covered_css | |
let covered_css = "/* Generated by Superfein CSS Coverage Tool \n" + | |
" ************************************* */ \n\n"; | |
for (const range of entry.ranges) { | |
// Iterate through the .json ranges | |
covered_css += entry.text.slice(range.start, range.end) + "\n"; | |
} | |
// Create and export each coverage CSS file | |
fs.writeFile("./css_assets/"+exportCSSFileName(entry.url), covered_css, function(err) { | |
if(err) { | |
return console.log(err); | |
} | |
console.log("The file "+exportCSSFileName(entry.url)+" was saved!"); | |
}); | |
} | |
} | |
await browser.close(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment