Skip to content

Instantly share code, notes, and snippets.

@aslushnikov
Last active February 11, 2023 06:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aslushnikov/d03eada6d12eedbd1b0a49d67f0b1d5b to your computer and use it in GitHub Desktop.
Save aslushnikov/d03eada6d12eedbd1b0a49d67f0b1d5b to your computer and use it in GitHub Desktop.
service worker network throttling with pptr
const puppeteer = require('puppeteer');
(async() => {
// Step 1: launch browser and open a new page.
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Step 2: PPTR.DEV has a service worker \m/
// Go there and wait for SW to register.
await page.goto('https://pptr.dev/');
const swTarget = await browser.waitForTarget(target => target.type() === 'service_worker');
// Step 3: Create a Chrome DevTools Protocol session to talk to service worker.
// Make sure to enable Runtime agent so that we can do evaluations inside SW.
const session = await swTarget.createCDPSession();
await session.send('Runtime.enable');
// Step 4: Fetch a dummy file from-inside SW and see how long it takes.
console.log(`Fetching WITHOUT network throttling: ${await measureAPIFetch(session)}ms`);
// Step 5: Enable network throttling.
// Exact numbers for this throttling are taken from Chrome DevTools front-end:
// https://github.com/chromium/chromium/blob/24c2704773b6d26f3fa65985dc54fb49eb449a6b/third_party/blink/renderer/devtools/front_end/sdk/NetworkManager.js#L247-L252
await session.send('Network.enable');
await session.send('Network.emulateNetworkConditions', {
offline: false,
latency: 400 * 5,
downloadThroughput: 500 * 1024 / 8 * .8,
uploadThroughput: 500 * 1024 / 8 * .8,
});
// Step 6: Fetch a dummy file from-inside SW and see how it long it takes now.
console.log(`Fetching WITH network throttling: ${await measureAPIFetch(session)}ms`);
// Step 7: Done. Close.
await browser.close();
})();
async function measureAPIFetch(session) {
return (await session.send('Runtime.evaluate', {
awaitPromise: true,
expression: `
(async function() {
const start = Date.now();
const response = await fetch('https://raw.githubusercontent.com/GoogleChrome/puppeteer/master/docs/api.md', {cache: "no-cache"});
const body = await response.text();
const end = Date.now();
return end - start;
})();
`,
})).result.value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment