Skip to content

Instantly share code, notes, and snippets.

@superfein
Last active February 13, 2023 07:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save superfein/20ed36d33c10d857d800a47f8a134b31 to your computer and use it in GitHub Desktop.
Save superfein/20ed36d33c10d857d800a47f8a134b31 to your computer and use it in GitHub Desktop.
Uses the Puppeteer node module to extract the coverage JS from Chrome, for a specific URL.
const puppeteer = require('puppeteer');
// Include to be able to export files with node
const fs = require('fs');
// This prepares the filenames for the coverage .js files
function exportJSFileName(url) {
// Remove https:// from the beginning of the string
// Remove .js* from the end of the string
var newFileName = url.substring(8, url.search("\\.js"));
// Replace all forward slashes with hyphens
newFileName = newFileName.replace(/\//g, "-");
// Return filename with .js concatenated at the end
return newFileName+".js";
}
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Enable JavaScript coverage
await Promise.all([
page.coverage.startJSCoverage()
]);
// Extract coverage JS from this URL
await page.goto('https://google.com');
// Disable JavaScript coverage
const jsCoverage = await Promise.all([
page.coverage.stopJSCoverage()
]);
// Investigate JS Coverage and Extract Used JS
const coverage = [...jsCoverage];
for (const entry of coverage[0]) {
// Init covered_js
let covered_js = "// Generated by Superfein JS Coverage Tool \n" +
"// ************************************ \n\n";
// Check if the js asset contains '.js' in the URL, if it does then export the coverage JS
// Ignoring inline scripts in the web page
if ( entry.url.search("\\.js") !== -1 ) {
for (const range of entry.ranges) {
// Iterate through the .json ranges
covered_js += entry.text.slice(range.start, range.end) + "\n";
}
// Create and export each coverage JS file
fs.writeFile("./js_assets/"+exportJSFileName(entry.url), covered_js, function(err) {
if(err) {
return console.log(err);
}
console.log("The file "+exportJSFileName(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