Repository navigation
feat: add Service Worker interception - #14321
Ross Wollman (rwoll) wants to merge 33 commits into
Conversation
|
Intercepting only requests sent from the service worker is not possible through the first condition argument, I was able to do something like this: test('should intercept only serviceworker request, not page', async ({ context, page, }) => {
await context.route('**/sw.js', route =>
route.fulfill({
contentType: 'text/javascript',
status: 200,
body: `
self.addEventListener('fetch', event => {
if (event.request.url.endsWith('/data.json')) {
event.respondWith(fetch(event.request));
}
});
`,
})
);
await context.route('**/data.json', async route => {
if (route.request().isServiceWorkerRequest()) {
return route.fulfill({
contentType: 'text/plain',
status: 200,
body: 'from sw',
});
} else {
return route.continue();
}
})
const [ sw ] = await Promise.all([
context.waitForEvent('serviceworker'),
page.goto(server.PREFIX + '/serviceworkers/empty/sw.html'),
]);
const response = await page.evaluate(() => fetch('/data.json').then(r => r.text()));
expect(response).toBe('from sw');
}); |
|
Meir Blachman (@Meir017) See this newly added test: 92e28e0#diff-f48a7787820cb49396256c1234745152eb05ca5a3f43b6d128ce0ee45eb6dff6R253 It aims to cover the intent of your scenario and passes. Notably it: (1) waits for the SW to be active, and (2) asserts the SW actually intercepted the request (according to the SW). Let me know if this covers your case! tl;dr: I think #14321 (comment) was invalid since it didn't wait for the SW to be active, so SW wasn't yet handling your request (which was still a page req at the time and was reported as such in the context.route). |
|
The following test has different behavior when the test.only('isServiceWorker() and serviceWorker() work', async ({ context, page, server }) => {
// context.route('**', (route) => route.continue());
const [worker] = await Promise.all([
context.waitForEvent('serviceworker'),
page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html')
]);
await page.evaluate(() => window['activationPromise']);
const [swReq, frameReq] = await Promise.all([
context.waitForEvent('request', r => r.url().endsWith('/inner.txt') && r.isServiceWorkerRequest()),
context.waitForEvent('request', r => r.url().endsWith('/inner.txt') && !r.isServiceWorkerRequest()),
page.evaluate(() => fetch('/inner.txt')),
]);
const [ url ] = await worker.evaluate(() => self['intercepted']);
expect(url).toMatch(/\/inner\.txt$/);
expect(swReq.frame).toThrow();
expect(swReq.isServiceWorkerRequest()).toBe(true);
expect(swReq.serviceWorker()).toBe(worker);
expect(frameReq.frame()).toBe(page.mainFrame());
expect(frameReq.isServiceWorkerRequest()).toBe(false);
expect(frameReq.serviceWorker()).toBe(null);
});With the following log line: diff --git a/packages/playwright-core/src/server/chromium/crNetworkManager.ts b/packages/playwright-core/src/server/chromium/crNetworkManager.ts
index fe1716c65..759a6c58d 100644
--- a/packages/playwright-core/src/server/chromium/crNetworkManager.ts
+++ b/packages/playwright-core/src/server/chromium/crNetworkManager.ts
@@ -348,6 +348,7 @@ export class CRNetworkManager {
this._responseExtraInfoTracker.responseReceived(event);
const request = this._requestIdToRequest.get(event.requestId);
+ console.log('eventLocation', this._serviceWorker ? 'sw' : 'page', 'fromServiceWorker:', event.response.fromServiceWorker, request?.request.url());
// FileUpload sends a response without a matching request.
if (!request)
return;We see the following with the test run as shown above: and the following when the context.route is added: The issue likley starts earlier in
In our simple example, how many times do we expect to see ^ This is a bit of word soup for me to look at on Monday 😄 |
Anecdotally, it's common for users to want to disable Service Workers while testing, so this provides a simple context option to do so. It also prepares us to land microsoft#14321 which requires us to have a point for folks to enable seeing Service Worker Requests as events (and allow for routing).
|
tests for https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/preloadResponse would be good here, I'm not sure if these scenario will work right now but they can be added later addEventListener("fetch", (event) => {
event.respondWith(
(async function () {
// Respond from the cache if we can
const cachedResponse = await caches.match(event.request);
if (cachedResponse) return cachedResponse;
// Else, use the preloaded response, if it's there
const response = await event.preloadResponse;
if (response) return response;
// Else try the network.
return fetch(event.request);
})()
);
}); |
|
Currently working on some of the opt-(in|out) logic. Once that's in, I'll update the description and open for review as that will be an actual candidate for landing and API review. |
Per https://www.w3.org/TR/service-workers/#origin-restriction and observing browser behavior. We don't expect the browser to ever even issue a request event if the main script is cross-origin.
|
Closing this to chop it up into a few different PRs |
…#14716) Adds Chromium support for Service Worker Networking (interception/routing, Request/Response events, and HAR). Resolves #1090. Depends on #14714 and #14714. Supercedes #14321. Follow up #14711. Landed upstream patches: - https://chromium-review.googlesource.com/c/chromium/src/+/3510917 - https://chromium-review.googlesource.com/c/chromium/src/+/3526571 - https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3566669 - https://chromium-review.googlesource.com/c/chromium/src/+/3544685 - https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3610924 - https://chromium-review.googlesource.com/c/chromium/src/+/3689949
Adds Service Worker Main Script Interception (CR-only) and Service Worker related utils:
Response.fulfilledByServiceWorkerserviceWorkers: "allow" | "block"context option (andtest.useoption)Resolves #1090
Resolves #14666
Supercedes #12565
Landed upstream patches:
Pending upstream patches (to resolve the failing test cases in this PR):
Since this Playwright change opts all users in by default, but the upstream pending patch is required to fix some rare failure modes, this Playwright PR should be followed up with a minor change that guards the installation of the new instrumentation based on CR major revision.