-
-
Save hhkaos/e869fbb5778a0d46fb3f44a36520f74b to your computer and use it in GitHub Desktop.
service worker network throttling with pptr
This file contains hidden or 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'); | |
(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