Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions cdp/raw_websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,47 +17,47 @@
*/

/**
* Shows how to use raw web sockets to send messages to the page using
* the DevTools protocol.
* Shows how to use raw WebSockets (via Node's built-in WebSocket) to send
* messages to the page using the Chrome DevTools Protocol.
* See https://chromedevtools.github.io/devtools-protocol/
*/

const {URL} = require('url');
const WebSocket = require('ws');
const puppeteer = require('puppeteer');
import puppeteer from 'puppeteer';

const url = process.env.URL || 'https://example.com';

(async() => {
const url = process.env.URL || 'https://developer.chrome.com/';

const browser = await puppeteer.launch();
const page = await browser.newPage();

// // 1. createCDPSession() is the easiest way to work with the raw DTP:
// const client = await page.target().createCDPSession();
// 1. page.createCDPSession() is the easiest way to work with raw CDP:
// const client = await page.createCDPSession();
// const version = await client.send('Browser.getVersion');
// console.log(version);

// 2.But you can also use raw websockets...
// 2. Or you can use raw WebSockets directly:

// Pull page's ws:// debugging url.
// Pull the page's ws:// debugging URL.
const wsUrl = new URL(browser.wsEndpoint());
const resp = await page.goto(`http://localhost:${wsUrl.port}/json`);
const {webSocketDebuggerUrl} = (await resp.json())[0];
const resp = await fetch(`http://localhost:${wsUrl.port}/json`);
const targets = await resp.json();
const {webSocketDebuggerUrl} = targets.find(t => t.type === 'page');

await page.goto(url); // Navigate to actual page.

// Connect to page's ws:// endpoint.
const ws = new WebSocket(webSocketDebuggerUrl).on('open', () => {
// Connect to the page's ws:// endpoint using Node's built-in WebSocket.
const ws = new WebSocket(webSocketDebuggerUrl);

ws.addEventListener('open', () => {
ws.send(JSON.stringify({
id: 1,
method: 'Runtime.evaluate',
params: {expression: 'document.title'} // return the page title.
params: {expression: 'document.title'}, // return the page title.
}));
}).on('message', async data => {
console.log('Title of page:', JSON.parse(data).result.result.value);
});

ws.addEventListener('message', async event => {
const {result} = JSON.parse(event.data);
console.log('Title of page:', result.result.value);
ws.close();
await browser.close();
});

})();
155 changes: 77 additions & 78 deletions code_coverage.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,14 @@
* different points of time during loading. Great for determining if a lazy loading strategy
* is paying off or working correctly.
*
* Install:
* npm i puppeteer chalk cli-table
* Run:
* URL=https://example.com node code_coverage.js
*/

const puppeteer = require('puppeteer');
const chalk = require('chalk');
const Table = require('cli-table');
import {stripVTControlCharacters, styleText} from 'node:util';
import puppeteer from 'puppeteer';

const URL = process.env.URL || 'https://www.chromestatus.com/features';
const URL = process.env.URL || 'https://chromestatus.com/roadmap';

const EVENTS = [
'domcontentloaded',
Expand All @@ -48,49 +45,70 @@ function formatBytesToKB(bytes) {
return `${bytes} bytes`;
}

function formatTable(headers, rows) {
const allRows = [headers, ...rows].map(row => row.map(String));
const widths = headers.map((_, col) =>
Math.max(...allRows.map(row => stripVTControlCharacters(row[col]).length))
);
const pad = (str, width) => str + ' '.repeat(width - stripVTControlCharacters(str).length);
const border = (left, mid, right) =>
styleText('gray', left + widths.map(w => '─'.repeat(w + 2)).join(mid) + right);
const formatRow = row =>
styleText('gray', '│') +
row.map((cell, i) => ` ${pad(cell, widths[i])} `).join(styleText('gray', '│')) +
styleText('gray', '│');

return [
border('┌', '┬', '┐'),
formatRow(headers.map(h => styleText('white', h))),
border('├', '┼', '┤'),
...rows.map(row => formatRow(row.map(String))),
border('└', '┴', '┘'),
].join('\n');
}

class UsageFormatter {
constructor(stats) {
this.stats = stats;
}

static eventLabel(event) {
// const maxEventLabelLen = EVENTS.reduce((currMax, event) => Math.max(currMax, event.length), 0);
// const eventLabel = event + ' '.repeat(maxEventLabelLen - event.length);
return chalk.magenta(event);
return styleText('magenta', event);
}

summary(used = this.stats.usedBytes, total = this.stats.totalBytes) {
const percent = Math.round((used / total) * 100);
const percent = total ? Math.round((used / total) * 100) : 0;
return `${formatBytesToKB(used)}/${formatBytesToKB(total)} (${percent}%)`;
}

shortSummary(used, total = this.stats.totalBytes) {
const percent = Math.round((used / total) * 100);
const percent = total ? Math.round((used / total) * 100) : 0;
return used ? `${formatBytesToKB(used)} (${percent}%)` : 0;
}

/**
* Constructors a bar chart for the % usage of each value.
* Constructs a bar chart for the % usage of each value.
* @param {!{jsUsed: number, cssUsed: number, totalBytes: number}=} stats Usage stats.
* @return {string}
*/
barGraph(stats = this.stats) {
// const MAX_TERMINAL_CHARS = process.stdout.columns;
const maxBarWidth = 30;

const jsSegment = ' '.repeat((stats.jsUsed / stats.totalBytes) * maxBarWidth);
const cssSegment = ' '.repeat((stats.cssUsed / stats.totalBytes) * maxBarWidth);
const unusedSegment = ' '.repeat(maxBarWidth - jsSegment.length - cssSegment.length);

return chalk.bgRedBright(jsSegment) + chalk.bgBlueBright(cssSegment) +
chalk.bgBlackBright(unusedSegment);
const jsLen = stats.totalBytes ? Math.round((stats.jsUsed / stats.totalBytes) * maxBarWidth) : 0;
const cssLen = stats.totalBytes ? Math.round((stats.cssUsed / stats.totalBytes) * maxBarWidth) : 0;
const unusedLen = Math.max(0, maxBarWidth - jsLen - cssLen);

return (
styleText('bgRedBright', ' '.repeat(jsLen)) +
styleText('bgBlueBright', ' '.repeat(cssLen)) +
styleText('bgGray', ' '.repeat(unusedLen))
);
}
}

const stats = new Map();

/**
* @param {!Object} coverage
* @param {!Array<!Object>} coverage
* @param {string} type Either "css" or "js" to indicate which type of coverage.
* @param {string} eventType The page event when the coverage was captured.
*/
Expand All @@ -110,7 +128,7 @@ function addUsage(coverage, type, eventType) {
get usedBytes() { return this.cssUsed + this.jsUsed; },
totalBytes: 0,
get percentUsed() {
return this.totalBytes ? Math.round(this.usedBytes / this.totalBytes * 100) : 0;
return this.totalBytes ? Math.round((this.usedBytes / this.totalBytes) * 100) : 0;
},
eventType,
url: entry.url,
Expand All @@ -127,30 +145,25 @@ function addUsage(coverage, type, eventType) {
}

async function collectCoverage() {
const browser = await puppeteer.launch({headless: true});
const browser = await puppeteer.launch();

// Do separate load for each event. See
// https://github.com/GoogleChrome/puppeteer/issues/1887
// https://github.com/puppeteer/puppeteer/issues/1887
const collectPromises = EVENTS.map(async event => {
console.log(`Collecting coverage @ ${UsageFormatter.eventLabel(event)}...`);

const page = await browser.newPage();

// page.on('response', async response => {
// console.log(response.request().url(), (await response.text()).length);
// });

await Promise.all([
page.coverage.startJSCoverage(),
page.coverage.startCSSCoverage()
page.coverage.startCSSCoverage(),
]);

await page.goto(URL, {waitUntil: event});
// await page.waitForNavigation({waitUntil: event});

const [jsCoverage, cssCoverage] = await Promise.all([
page.coverage.stopJSCoverage(),
page.coverage.stopCSSCoverage()
page.coverage.stopCSSCoverage(),
]);

addUsage(cssCoverage, 'css', event);
Expand All @@ -160,76 +173,62 @@ async function collectCoverage() {
});

await Promise.all(collectPromises);

return browser.close();
await browser.close();
}

(async() => {

await collectCoverage();

for (const [url, vals] of stats) {
console.log('\n' + chalk.cyan(url));

const table = new Table({
// chars: {mid: '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''},
head: [
'Event',
`${chalk.bgRedBright(' JS ')} ${chalk.bgBlueBright(' CSS ')} % used`,
'JS used',
'CSS used',
'Total bytes used'
],
// style : {compact : true, 'padding-left' : 0}
style: {head: ['white'], border: ['grey']}
// colWidths: [20, 20]
});

EVENTS.forEach(event => {
console.log('\n' + styleText('cyan', url));

const headers = [
'Event',
`${styleText('bgRedBright', ' JS ')} ${styleText('bgBlueBright', ' CSS ')} % used`,
'JS used',
'CSS used',
'Total bytes used',
];

const rows = [];
for (const event of EVENTS) {
const usageForEvent = vals.filter(val => val.eventType === event);

if (usageForEvent.length) {
for (const stats of usageForEvent) {
// totalBytes += stats.totalBytes;
// totalUsedBytes += stats.usedBytes;

const formatter = new UsageFormatter(stats);
table.push([
UsageFormatter.eventLabel(stats.eventType),
for (const entryStats of usageForEvent) {
const formatter = new UsageFormatter(entryStats);
rows.push([
UsageFormatter.eventLabel(entryStats.eventType),
formatter.barGraph(),
formatter.shortSummary(stats.jsUsed), // !== 0 ? `${formatBytesToKB(stats.jsUsed)}KB` : 0,
formatter.shortSummary(stats.cssUsed),
formatter.summary()
formatter.shortSummary(entryStats.jsUsed),
formatter.shortSummary(entryStats.cssUsed),
formatter.summary(),
]);
}
} else {
table.push([UsageFormatter.eventLabel(event), 'no usage found', '-', '-', '-']);
rows.push([UsageFormatter.eventLabel(event), 'no usage found', '-', '-', '-']);
}
});
}

console.log(table.toString());
console.log(formatTable(headers, rows));
}

// Print total usage for each event.
// console.log('\n');
EVENTS.forEach(event => {
for (const event of EVENTS) {
let totalBytes = 0;
let totalUsedBytes = 0;

const metrics = Array.from(stats.values());
const statsForEvent = metrics.map(eventStatsForUrl => {
const statsForEvent = eventStatsForUrl.filter(stat => stat.eventType === event)[0];
// TODO: need to sum max totalBytes. Currently ignores stats if event didn't
// have an entry. IOW, all total numerators should be max totalBytes seen for that event.
for (const eventStatsForUrl of stats.values()) {
const statsForEvent = eventStatsForUrl.find(stat => stat.eventType === event);
if (statsForEvent) {
totalBytes += statsForEvent.totalBytes;
totalUsedBytes += statsForEvent.usedBytes;
}
});

const percentUsed = Math.round(totalUsedBytes / totalBytes * 100);
}

console.log(`Total used @ ${chalk.magenta(event)}: ${formatBytesToKB(totalUsedBytes)}/${formatBytesToKB(totalBytes)} (${percentUsed}%)`);
});
const percentUsed = totalBytes ? Math.round((totalUsedBytes / totalBytes) * 100) : 0;

})();
console.log(
`Total used @ ${styleText('magenta', event)}: ` +
`${formatBytesToKB(totalUsedBytes)}/${formatBytesToKB(totalBytes)} (${percentUsed}%)`
);
}
45 changes: 20 additions & 25 deletions connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,49 +19,44 @@
/**
* @fileoverview
*
* Demonstrates how to use puppeteer.connect() to re-connect to instance of
* Demonstrates how to use puppeteer.connect() to re-connect to an instance of
* Chrome that's already running with remote debugging enabled.
*
* These first time you run this script, it will launch Chrome and print
* The first time you run this script, it will launch Chrome and print
* the remote debugging websocket url.
*
* node connect.js
*
* The second time you run the script, pass the websocket URL as an env variable.
* Puppeteer will reconnect that to the browser instance running instead of
* Puppeteer will reconnect to the running browser instance instead of
* launching a new browser.
*
* wsURL=ws://127.0.0.1:9222/devtools/browser/72775377-7f73-4436 node connect.js
*/

const path = require('path');
const puppeteer = require('puppeteer');
import path from 'node:path';
import puppeteer from 'puppeteer';

const browserWSEndpoint = process.env.wsURL || null;

(async() => {

if (!browserWSEndpoint) {
const browser = await puppeteer.launch({
handleSIGINT: false, // so Chrome doesn't exit when we quit Node.
headless: false // to see what's happening
});

console.log('1. Quit this script (cmd/ctrl+C).');
console.log('2. Chrome will still be running.');
console.log('4. Re-return the script with:');
console.log(` wsURL=${browser.wsEndpoint()} node ${path.basename(__filename)}`);
console.log('5. Puppeteer will reconnect to the existing Chrome instead of launching a new browser.');

return;
}

if (!browserWSEndpoint) {
const browser = await puppeteer.launch({
handleSIGINT: false, // so Chrome doesn't exit when we quit Node.
headless: false, // to see what's happening
});

console.log('1. Quit this script (cmd/ctrl+C).');
console.log('2. Chrome will still be running.');
console.log('3. Re-run the script with:');
console.log(` wsURL=${browser.wsEndpoint()} node ${path.basename(import.meta.filename)}`);
console.log('4. Puppeteer will reconnect to the existing Chrome instead of launching a new browser.');
} else {
console.log('Reconnecting to existing Chrome....');
const browser = await puppeteer.connect({browserWSEndpoint});
const page = await browser.newPage();
await page.goto('https://example.com');
await page.goto('https://developer.chrome.com/');

console.log(`Page title:`, await page.title());
console.log('Page title:', await page.title());

await browser.close();
})();
}
Loading
Loading