Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(routeWebSocket): make it work with http(s) baseURL (#33457)

Dmitry Gozman697d7a40b1d9
diff --git a/packages/playwright-core/src/utils/isomorphic/urlMatch.ts b/packages/playwright-core/src/utils/isomorphic/urlMatch.ts
index b20d47d220..f5d6efb70d 100644
--- a/packages/playwright-core/src/utils/isomorphic/urlMatch.ts
+++ b/packages/playwright-core/src/utils/isomorphic/urlMatch.ts
@@ -97,8 +97,12 @@ export function urlMatchesEqual(match1: URLMatch, match2: URLMatch) {
export function urlMatches(baseURL: string | undefined, urlString: string, match: URLMatch | undefined): boolean {
if (match === undefined || match === '')
return true;
- if (isString(match) && !match.startsWith('*'))
+ if (isString(match) && !match.startsWith('*')) {
+ // Allow http(s) baseURL to match ws(s) urls.
+ if (baseURL && /^https?:\/\//.test(baseURL) && /^wss?:\/\//.test(urlString))
+ baseURL = baseURL.replace(/^http/, 'ws');
match = constructURLBasedOnBaseURL(baseURL, match);
+ }
if (isString(match))
match = globToRegex(match);
if (isRegExp(match))
diff --git a/tests/library/route-web-socket.spec.ts b/tests/library/route-web-socket.spec.ts
index d3c3607c99..a4c32c874f 100644
--- a/tests/library/route-web-socket.spec.ts
+++ b/tests/library/route-web-socket.spec.ts
@@ -539,3 +539,26 @@ test('should work with no trailing slash', async ({ page, server }) => {
await expect.poll(() => log).toEqual(['query']);
expect(await page.evaluate(() => window.log)).toEqual(['response']);
});
+
+test('should work with baseURL', async ({ contextFactory, server }) => {
+ const context = await contextFactory({ baseURL: 'http://localhost:' + server.PORT });
+ const page = await context.newPage();
+
+ await page.routeWebSocket('/ws', ws => {
+ ws.onMessage(message => {
+ ws.send(message);
+ });
+ });
+
+ await setupWS(page, server.PORT, 'blob');
+
+ await page.evaluate(async () => {
+ await window.wsOpened;
+ window.ws.send('echo');
+ });
+
+ await expect.poll(() => page.evaluate(() => window.log)).toEqual([
+ 'open',
+ `message: data=echo origin=ws://localhost:${server.PORT} lastEventId=`,
+ ]);
+});