Skip to content

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

feat: toHaveURLPattern (#38925)

Simon Knottcd36686c07f6
diff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.md
index 773ee276ff..8c4ec83ff4 100644
--- a/docs/src/api/class-browsercontext.md
+++ b/docs/src/api/class-browsercontext.md
@@ -1173,6 +1173,14 @@ Enabling routing disables http cache.
### param: BrowserContext.route.url
* since: v1.8
+* langs: js
+- `url` <[string]|[RegExp]|[URLPattern]|[function]\([URL]\):[boolean]>
+
+A glob pattern, regex pattern, URL pattern, or predicate that receives a [URL] to match during routing. If [`option: Browser.newContext.baseURL`] is set in the context options and the provided URL is a string that does not start with `*`, it is resolved using the [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
+
+### param: BrowserContext.route.url
+* since: v1.8
+* langs: python, csharp, java
- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]>
A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If [`option: Browser.newContext.baseURL`] is set in the context options and the provided URL is a string that does not start with `*`, it is resolved using the [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
@@ -1560,9 +1568,18 @@ routes for the [`param: url`].
### param: BrowserContext.unroute.url
* since: v1.8
+* langs: js
+- `url` <[string]|[RegExp]|[URLPattern]|[function]\([URL]\):[boolean]>
+
+A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] used to register a routing with
+[`method: BrowserContext.route`].
+
+### param: BrowserContext.unroute.url
+* since: v1.8
+* langs: python, csharp, java
- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]>
-A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with
+A glob pattern, regex pattern, or predicate receiving [URL] used to register a routing with
[`method: BrowserContext.route`].
### param: BrowserContext.unroute.handler
diff --git a/docs/src/api/class-frame.md b/docs/src/api/class-frame.md
index f9c366e427..531901bcbb 100644
--- a/docs/src/api/class-frame.md
+++ b/docs/src/api/class-frame.md
@@ -2077,7 +2077,10 @@ a navigation.
### param: Frame.waitForNavigation.action = %%-csharp-wait-for-event-action-%%
* since: v1.12
-### option: Frame.waitForNavigation.url = %%-wait-for-navigation-url-%%
+### option: Frame.waitForNavigation.url = %%-js-wait-for-navigation-url-%%
+* since: v1.8
+
+### option: Frame.waitForNavigation.url = %%-python-csharp-java-wait-for-navigation-url-%%
* since: v1.8
### option: Frame.waitForNavigation.waitUntil = %%-navigation-wait-until-%%
@@ -2273,7 +2276,10 @@ await frame.ClickAsync("a.delayed-navigation"); // clicking the link will indire
await frame.WaitForURLAsync("**/target.html");
```
-### param: Frame.waitForURL.url = %%-wait-for-navigation-url-%%
+### param: Frame.waitForURL.url = %%-js-wait-for-navigation-url-%%
+* since: v1.11
+
+### param: Frame.waitForURL.url = %%-python-csharp-java-wait-for-navigation-url-%%
* since: v1.11
### option: Frame.waitForURL.timeout = %%-navigation-timeout-%%
diff --git a/docs/src/api/class-page.md b/docs/src/api/class-page.md
index 481a251deb..f3ef243d35 100644
--- a/docs/src/api/class-page.md
+++ b/docs/src/api/class-page.md
@@ -2170,7 +2170,7 @@ var frame = page.FrameByUrl(".*domain.*");
* langs: js
- `frameSelector` <[string]|[Object]>
- `name` ?<[string]> Frame name specified in the `iframe`'s `name` attribute. Optional.
- - `url` ?<[string]|[RegExp]|[function]\([URL]\):[boolean]> A glob pattern, regex pattern or predicate receiving
+ - `url` ?<[string]|[RegExp]|[URLPattern]|[function]\([URL]\):[boolean]> A glob pattern, regex pattern, URL pattern, or predicate receiving
frame's `url` as a [URL] object. Optional.
Frame name or other frame lookup options.
@@ -3684,6 +3684,14 @@ Enabling routing disables http cache.
### param: Page.route.url
* since: v1.8
+* langs: js
+- `url` <[string]|[RegExp]|[URLPattern]|[function]\([URL]\):[boolean]>
+
+A glob pattern, regex pattern, URL pattern, or predicate that receives a [URL] to match during routing. If [`option: Browser.newContext.baseURL`] is set in the context options and the provided URL is a string that does not start with `*`, it is resolved using the [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
+
+### param: Page.route.url
+* since: v1.8
+* langs: python, csharp, java
- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]>
A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If [`option: Browser.newContext.baseURL`] is set in the context options and the provided URL is a string that does not start with `*`, it is resolved using the [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
@@ -3816,6 +3824,14 @@ await page.RouteWebSocketAsync("/ws", ws => {
### param: Page.routeWebSocket.url
* since: v1.48
+* langs: js
+- `url` <[string]|[RegExp]|[URLPattern]|[function]\([URL]\):[boolean]>
+
+Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the [`option: Browser.newContext.baseURL`] context option.
+
+### param: Page.routeWebSocket.url
+* since: v1.48
+* langs: python, csharp, java
- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]>
Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the [`option: Browser.newContext.baseURL`] context option.
@@ -4341,9 +4357,17 @@ the [`param: url`].
### param: Page.unroute.url
* since: v1.8
+* langs: js
+- `url` <[string]|[RegExp]|[URLPattern]|[function]\([URL]\):[boolean]>
+
+A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while routing.
+
+### param: Page.unroute.url
+* since: v1.8
+* langs: python, csharp, java
- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]>
-A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
+A glob pattern, regex pattern, or predicate receiving [URL] to match while routing.
### param: Page.unroute.handler
* since: v1.8
@@ -4840,7 +4864,10 @@ a navigation.
### param: Page.waitForNavigation.action = %%-csharp-wait-for-event-action-%%
* since: v1.12
-### option: Page.waitForNavigation.url = %%-wait-for-navigation-url-%%
+### option: Page.waitForNavigation.url = %%-js-wait-for-navigation-url-%%
+* since: v1.8
+
+### option: Page.waitForNavigation.url = %%-python-csharp-java-wait-for-navigation-url-%%
* since: v1.8
### option: Page.waitForNavigation.waitUntil = %%-navigation-wait-until-%%
@@ -5377,7 +5404,10 @@ await page.ClickAsync("a.delayed-navigation"); // clicking the link will indirec
await page.WaitForURLAsync("**/target.html");
```
-### param: Page.waitForURL.url = %%-wait-for-navigation-url-%%
+### param: Page.waitForURL.url = %%-js-wait-for-navigation-url-%%
+* since: v1.11
+
+### param: Page.waitForURL.url = %%-python-csharp-java-wait-for-navigation-url-%%
* since: v1.11
### option: Page.waitForURL.timeout = %%-navigation-timeout-%%
diff --git a/docs/src/api/class-pageassertions.md b/docs/src/api/class-pageassertions.md
index 6420735f2b..49e00880ee 100644
--- a/docs/src/api/class-pageassertions.md
+++ b/docs/src/api/class-pageassertions.md
@@ -302,6 +302,9 @@ await expect(page).toHaveURL('https://playwright.dev/docs/intro');
// Check for the page URL to contain 'doc', followed by an optional 's', followed by '/'
await expect(page).toHaveURL(/docs?\//);
+// Check for the page URL to match the URL pattern
+await expect(page).toHaveURL(new URLPattern({ pathname: '/docs/*' }));
+
// Check for the predicate to be satisfied
// For example: verify query strings
await expect(page).toHaveURL(url => {
@@ -337,7 +340,7 @@ await Expect(Page).ToHaveURLAsync(new Regex(".*checkout"));
### param: PageAssertions.toHaveURL.url
* since: v1.18
* langs: js
-- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]>
+- `url` <[string]|[RegExp]|[URLPattern]|[function]\([URL]\):[boolean]>
Expected URL string, RegExp, or predicate receiving [URL] to match.
When [`option: Browser.newContext.baseURL`] is provided via the context options and the `url` argument is a string, the two values are merged via the [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor and used for the comparison against the current browser URL.
diff --git a/docs/src/api/params.md b/docs/src/api/params.md
index 69257b93db..2b2587acdc 100644
--- a/docs/src/api/params.md
+++ b/docs/src/api/params.md
@@ -890,10 +890,19 @@ Options to select. If the `<select>` has the `multiple` attribute, all matching
first option matching one of the passed options is selected. String values are matching both values and labels. Option
is considered matching if all specified properties match.
-## wait-for-navigation-url
+## js-wait-for-navigation-url
+* langs: js
+- `url` <[string]|[RegExp]|[URLPattern]|[function]\([URL]\):[boolean]>
+
+A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while waiting for the navigation. Note that if
+the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
+equal to the string.
+
+## python-csharp-java-wait-for-navigation-url
+* langs: python, csharp, java
- `url` <[string]|[RegExp]|[function]\([URL]\):[boolean]>
-A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
+A glob pattern, regex pattern, or predicate receiving [URL] to match while waiting for the navigation. Note that if
the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
equal to the string.
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index f174c4344d..add5421430 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -20,6 +20,10 @@ import { ReadStream } from 'fs';
import { Protocol } from './protocol';
import { Serializable, EvaluationArgument, PageFunction, PageFunctionOn, SmartHandle, ElementHandleForTag, BindingSource } from './structs';
+// Use the global URLPattern type if available (Node.js 22+, modern browsers),
+// otherwise fall back to `never` so it disappears from union types.
+type URLPattern = typeof globalThis extends { URLPattern: infer T } ? T : never;
+
type PageWaitForSelectorOptionsNotHidden = PageWaitForSelectorOptions & {
state?: 'visible'|'attached';
};
@@ -2840,9 +2844,9 @@ export interface Page {
name?: string;
/**
- * A glob pattern, regex pattern or predicate receiving frame's `url` as a [URL] object. Optional.
+ * A glob pattern, regex pattern, URL pattern, or predicate receiving frame's `url` as a [URL] object. Optional.
*/
- url?: string|RegExp|((url: URL) => boolean);
+ url?: string|RegExp|URLPattern|((url: URL) => boolean);
}): null|Frame;
/**
@@ -4097,14 +4101,14 @@ export interface Page {
*
* **NOTE** Enabling routing disables http cache.
*
- * @param url A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate that receives a [URL] to match during routing. If
* [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) is set in the
* context options and the provided URL is a string that does not start with `*`, it is resolved using the
* [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
* @param handler handler function to route the request.
* @param options
*/
- route(url: string|RegExp|((url: URL) => boolean), handler: ((route: Route, request: Request) => Promise<any>|any), options?: {
+ route(url: string|RegExp|URLPattern|((url: URL) => boolean), handler: ((route: Route, request: Request) => Promise<any>|any), options?: {
/**
* How often a route should be used. By default it will be used every time.
*/
@@ -4185,7 +4189,7 @@ export interface Page {
* [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) context option.
* @param handler Handler function to route the WebSocket.
*/
- routeWebSocket(url: string|RegExp|((url: URL) => boolean), handler: ((websocketroute: WebSocketRoute) => Promise<any>|any)): Promise<void>;
+ routeWebSocket(url: string|RegExp|URLPattern|((url: URL) => boolean), handler: ((websocketroute: WebSocketRoute) => Promise<any>|any)): Promise<void>;
/**
* Returns the buffer with the captured screenshot.
@@ -4776,10 +4780,10 @@ export interface Page {
* [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route). When
* [`handler`](https://playwright.dev/docs/api/class-page#page-unroute-option-handler) is not specified, removes all
* routes for the [`url`](https://playwright.dev/docs/api/class-page#page-unroute-option-url).
- * @param url A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while routing.
* @param handler Optional handler function to route the request.
*/
- unroute(url: string|RegExp|((url: URL) => boolean), handler?: ((route: Route, request: Request) => Promise<any>|any)): Promise<void>;
+ unroute(url: string|RegExp|URLPattern|((url: URL) => boolean), handler?: ((route: Route, request: Request) => Promise<any>|any)): Promise<void>;
/**
* Removes all routes created with
@@ -5111,11 +5115,11 @@ export interface Page {
timeout?: number;
/**
- * A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- * the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- * equal to the string.
+ * A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while waiting for the navigation.
+ * Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that
+ * is exactly equal to the string.
*/
- url?: string|RegExp|((url: URL) => boolean);
+ url?: string|RegExp|URLPattern|((url: URL) => boolean);
/**
* When to consider operation succeeded, defaults to `load`. Events can be either:
@@ -5229,12 +5233,12 @@ export interface Page {
* await page.waitForURL('**\/target.html');
* ```
*
- * @param url A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- * the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- * equal to the string.
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while waiting for the navigation.
+ * Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that
+ * is exactly equal to the string.
* @param options
*/
- waitForURL(url: string|RegExp|((url: URL) => boolean), options?: {
+ waitForURL(url: string|RegExp|URLPattern|((url: URL) => boolean), options?: {
/**
* Maximum operation time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via
* `navigationTimeout` option in the config, or by using the
@@ -8294,11 +8298,11 @@ export interface Frame {
timeout?: number;
/**
- * A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- * the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- * equal to the string.
+ * A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while waiting for the navigation.
+ * Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that
+ * is exactly equal to the string.
*/
- url?: string|RegExp|((url: URL) => boolean);
+ url?: string|RegExp|URLPattern|((url: URL) => boolean);
/**
* When to consider operation succeeded, defaults to `load`. Events can be either:
@@ -8335,12 +8339,12 @@ export interface Frame {
* await frame.waitForURL('**\/target.html');
* ```
*
- * @param url A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- * the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- * equal to the string.
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while waiting for the navigation.
+ * Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that
+ * is exactly equal to the string.
* @param options
*/
- waitForURL(url: string|RegExp|((url: URL) => boolean), options?: {
+ waitForURL(url: string|RegExp|URLPattern|((url: URL) => boolean), options?: {
/**
* Maximum operation time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via
* `navigationTimeout` option in the config, or by using the
@@ -9418,14 +9422,14 @@ export interface BrowserContext {
*
* **NOTE** Enabling routing disables http cache.
*
- * @param url A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate that receives a [URL] to match during routing. If
* [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) is set in the
* context options and the provided URL is a string that does not start with `*`, it is resolved using the
* [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
* @param handler handler function to route the request.
* @param options
*/
- route(url: string|RegExp|((url: URL) => boolean), handler: ((route: Route, request: Request) => Promise<any>|any), options?: {
+ route(url: string|RegExp|URLPattern|((url: URL) => boolean), handler: ((route: Route, request: Request) => Promise<any>|any), options?: {
/**
* How often a route should be used. By default it will be used every time.
*/
@@ -9738,12 +9742,12 @@ export interface BrowserContext {
* When [`handler`](https://playwright.dev/docs/api/class-browsercontext#browser-context-unroute-option-handler) is
* not specified, removes all routes for the
* [`url`](https://playwright.dev/docs/api/class-browsercontext#browser-context-unroute-option-url).
- * @param url A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] used to register a routing with
* [browserContext.route(url, handler[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-route).
* @param handler Optional handler function used to register a routing with
* [browserContext.route(url, handler[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-route).
*/
- unroute(url: string|RegExp|((url: URL) => boolean), handler?: ((route: Route, request: Request) => Promise<any>|any)): Promise<void>;
+ unroute(url: string|RegExp|URLPattern|((url: URL) => boolean), handler?: ((route: Route, request: Request) => Promise<any>|any)): Promise<void>;
/**
* Removes all routes created with
diff --git a/packages/playwright-core/src/client/network.ts b/packages/playwright-core/src/client/network.ts
index 727090961a..4541decac5 100644
--- a/packages/playwright-core/src/client/network.ts
+++ b/packages/playwright-core/src/client/network.ts
@@ -23,10 +23,10 @@ import { Waiter } from './waiter';
import { Worker } from './worker';
import { assert } from '../utils/isomorphic/assert';
import { headersObjectToArray } from '../utils/isomorphic/headers';
-import { urlMatches } from '../utils/isomorphic/urlMatch';
+import { serializeURLMatch, urlMatches } from '../utils/isomorphic/urlMatch';
import { LongStandingScope, ManualPromise } from '../utils/isomorphic/manualPromise';
import { MultiMap } from '../utils/isomorphic/multimap';
-import { isRegExp, isString } from '../utils/isomorphic/rtti';
+import { isString } from '../utils/isomorphic/rtti';
import { rewriteErrorMessage } from '../utils/isomorphic/stackTrace';
import { getMimeTypeForPath } from '../utils/isomorphic/mimeType';
@@ -587,10 +587,9 @@ export class WebSocketRouteHandler {
const patterns: channels.BrowserContextSetWebSocketInterceptionPatternsParams['patterns'] = [];
let all = false;
for (const handler of handlers) {
- if (isString(handler.url))
- patterns.push({ glob: handler.url });
- else if (isRegExp(handler.url))
- patterns.push({ regexSource: handler.url.source, regexFlags: handler.url.flags });
+ const serialized = serializeURLMatch(handler.url);
+ if (serialized)
+ patterns.push(serialized);
else
all = true;
}
@@ -828,10 +827,9 @@ export class RouteHandler {
const patterns: channels.BrowserContextSetNetworkInterceptionPatternsParams['patterns'] = [];
let all = false;
for (const handler of handlers) {
- if (isString(handler.url))
- patterns.push({ glob: handler.url });
- else if (isRegExp(handler.url))
- patterns.push({ regexSource: handler.url.source, regexFlags: handler.url.flags });
+ const serialized = serializeURLMatch(handler.url);
+ if (serialized)
+ patterns.push(serialized);
else
all = true;
}
diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.ts
index 3ce0a40bbf..37ede45c18 100644
--- a/packages/playwright-core/src/protocol/validator.ts
+++ b/packages/playwright-core/src/protocol/validator.ts
@@ -97,6 +97,16 @@ scheme.SelectorEngine = tObject({
source: tString,
contentScript: tOptional(tBoolean),
});
+scheme.URLPattern = tObject({
+ hash: tString,
+ hostname: tString,
+ password: tString,
+ pathname: tString,
+ port: tString,
+ protocol: tString,
+ search: tString,
+ username: tString,
+});
scheme.SetNetworkCookie = tObject({
name: tString,
value: tString,
@@ -1029,6 +1039,7 @@ scheme.BrowserContextSetNetworkInterceptionPatternsParams = tObject({
glob: tOptional(tString),
regexSource: tOptional(tString),
regexFlags: tOptional(tString),
+ urlPattern: tOptional(tType('URLPattern')),
})),
});
scheme.BrowserContextSetNetworkInterceptionPatternsResult = tOptional(tObject({}));
@@ -1037,6 +1048,7 @@ scheme.BrowserContextSetWebSocketInterceptionPatternsParams = tObject({
glob: tOptional(tString),
regexSource: tOptional(tString),
regexFlags: tOptional(tString),
+ urlPattern: tOptional(tType('URLPattern')),
})),
});
scheme.BrowserContextSetWebSocketInterceptionPatternsResult = tOptional(tObject({}));
@@ -1336,6 +1348,7 @@ scheme.PageSetNetworkInterceptionPatternsParams = tObject({
glob: tOptional(tString),
regexSource: tOptional(tString),
regexFlags: tOptional(tString),
+ urlPattern: tOptional(tType('URLPattern')),
})),
});
scheme.PageSetNetworkInterceptionPatternsResult = tOptional(tObject({}));
@@ -1344,6 +1357,7 @@ scheme.PageSetWebSocketInterceptionPatternsParams = tObject({
glob: tOptional(tString),
regexSource: tOptional(tString),
regexFlags: tOptional(tString),
+ urlPattern: tOptional(tType('URLPattern')),
})),
});
scheme.PageSetWebSocketInterceptionPatternsResult = tOptional(tObject({}));
diff --git a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
index 9f38c825a6..45a20e33c6 100644
--- a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
@@ -31,7 +31,7 @@ import { TracingDispatcher } from './tracingDispatcher';
import { WebSocketRouteDispatcher } from './webSocketRouteDispatcher';
import { WritableStreamDispatcher } from './writableStreamDispatcher';
import { createGuid } from '../utils/crypto';
-import { urlMatches } from '../../utils/isomorphic/urlMatch';
+import { deserializeURLMatch, urlMatches } from '../../utils/isomorphic/urlMatch';
import { Recorder } from '../recorder';
import { RecorderApp } from '../recorder/recorderApp';
import { ElementHandleDispatcher } from './elementHandlerDispatcher';
@@ -45,6 +45,7 @@ import type { InitScript, Page, PageBinding } from '../page';
import type { DispatcherScope } from './dispatcher';
import type * as channels from '@protocol/channels';
import type { Progress } from '@protocol/progress';
+import type { URLMatch } from '../../utils/isomorphic/urlMatch';
export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channels.BrowserContextChannel, DispatcherScope> implements channels.BrowserContextChannel {
_type_EventTarget = true;
@@ -57,7 +58,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel
private _dialogHandler: (dialog: Dialog) => boolean;
private _clockPaused = false;
private _requestInterceptor: RouteHandler;
- private _interceptionUrlMatchers: (string | RegExp)[] = [];
+ private _interceptionUrlMatchers: URLMatch[] = [];
private _routeWebSocketInitScript: InitScript | undefined;
static from(parentScope: DispatcherScope, context: BrowserContext): BrowserContextDispatcher {
@@ -318,7 +319,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel
await this._context.removeRequestInterceptor(this._requestInterceptor);
this._interceptionUrlMatchers = [];
} else {
- this._interceptionUrlMatchers = params.patterns.map(pattern => pattern.regexSource ? new RegExp(pattern.regexSource, pattern.regexFlags!) : pattern.glob!);
+ this._interceptionUrlMatchers = params.patterns.map(deserializeURLMatch);
if (!hadMatchers)
await this._context.addRequestInterceptor(progress, this._requestInterceptor);
}
diff --git a/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts b/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts
index 6eef750677..c34ab69857 100644
--- a/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts
@@ -26,7 +26,7 @@ import { ResponseDispatcher } from './networkDispatchers';
import { RouteDispatcher, WebSocketDispatcher } from './networkDispatchers';
import { WebSocketRouteDispatcher } from './webSocketRouteDispatcher';
import { SdkObject } from '../instrumentation';
-import { urlMatches } from '../../utils/isomorphic/urlMatch';
+import { deserializeURLMatch, urlMatches } from '../../utils/isomorphic/urlMatch';
import { PageAgentDispatcher } from './pageAgentDispatcher';
import type { Artifact } from '../artifact';
@@ -41,6 +41,7 @@ import type { RouteHandler } from '../network';
import type { InitScript, PageBinding } from '../page';
import type * as channels from '@protocol/channels';
import type { Progress } from '@protocol/progress';
+import type { URLMatch } from '../../utils/isomorphic/urlMatch';
export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, BrowserContextDispatcher> implements channels.PageChannel {
_type_EventTarget = true;
@@ -51,7 +52,7 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Brows
private _bindings: PageBinding[] = [];
private _initScripts: InitScript[] = [];
private _requestInterceptor: RouteHandler;
- private _interceptionUrlMatchers: (string | RegExp)[] = [];
+ private _interceptionUrlMatchers: URLMatch[] = [];
private _routeWebSocketInitScript: InitScript | undefined;
private _locatorHandlers = new Set<number>();
private _jsCoverageActive = false;
@@ -201,7 +202,7 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Brows
await this._page.removeRequestInterceptor(this._requestInterceptor);
this._interceptionUrlMatchers = [];
} else {
- this._interceptionUrlMatchers = params.patterns.map(pattern => pattern.regexSource ? new RegExp(pattern.regexSource, pattern.regexFlags!) : pattern.glob!);
+ this._interceptionUrlMatchers = params.patterns.map(deserializeURLMatch);
if (!hadMatchers)
await this._page.addRequestInterceptor(progress, this._requestInterceptor);
}
diff --git a/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts b/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts
index 53384dded9..b32000341b 100644
--- a/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts
@@ -19,7 +19,7 @@ import { Dispatcher } from './dispatcher';
import { PageDispatcher } from './pageDispatcher';
import * as rawWebSocketMockSource from '../../generated/webSocketMockSource';
import { SdkObject } from '../instrumentation';
-import { urlMatches } from '../../utils/isomorphic/urlMatch';
+import { deserializeURLMatch, urlMatches } from '../../utils/isomorphic/urlMatch';
import { eventsHelper } from '../utils/eventsHelper';
import type { BrowserContextDispatcher } from './browserContextDispatcher';
@@ -161,8 +161,7 @@ export class WebSocketRouteDispatcher extends Dispatcher<SdkObject, channels.Web
function matchesPattern(dispatcher: PageDispatcher | BrowserContextDispatcher, baseURL: string | undefined, url: string) {
for (const pattern of dispatcher._webSocketInterceptionPatterns || []) {
- const urlMatch = pattern.regexSource ? new RegExp(pattern.regexSource, pattern.regexFlags) : pattern.glob;
- if (urlMatches(baseURL, url, urlMatch, true))
+ if (urlMatches(baseURL, url, deserializeURLMatch(pattern), true))
return true;
}
return false;
diff --git a/packages/playwright-core/src/utils/isomorphic/urlMatch.ts b/packages/playwright-core/src/utils/isomorphic/urlMatch.ts
index 00cdfc019b..590d90d6e2 100644
--- a/packages/playwright-core/src/utils/isomorphic/urlMatch.ts
+++ b/packages/playwright-core/src/utils/isomorphic/urlMatch.ts
@@ -82,7 +82,78 @@ function isRegExp(obj: any): obj is RegExp {
return obj instanceof RegExp || Object.prototype.toString.call(obj) === '[object RegExp]';
}
-export type URLMatch = string | RegExp | ((url: URL) => boolean);
+export type URLMatch = string | RegExp | ((url: URL) => boolean) | URLPattern;
+// URLPattern is not in @types/node@18, so we polyfill it ourselves
+export type URLPattern = {
+ test(input: string | URL): boolean;
+ hash: string;
+ hostname: string;
+ password: string;
+ pathname: string;
+ port: string;
+ protocol: string;
+ search: string;
+ username: string;
+};
+
+// @ts-expect-error URLPattern is not in @types/node yet
+// eslint-disable-next-line no-restricted-globals
+export const isURLPattern = (v: unknown): v is URLPattern => typeof globalThis.URLPattern === 'function' && v instanceof globalThis.URLPattern;
+
+export function serializeURLPattern(v: URLPattern) {
+ return {
+ hash: v.hash,
+ hostname: v.hostname,
+ password: v.password,
+ pathname: v.pathname,
+ port: v.port,
+ protocol: v.protocol,
+ search: v.search,
+ username: v.username,
+ };
+}
+
+export type SerializedURLMatch = { glob?: string, regexSource?: string, regexFlags?: string, urlPattern?: ReturnType<typeof serializeURLPattern> };
+
+export function serializeURLMatch(match: URLMatch): SerializedURLMatch | undefined {
+ if (isString(match))
+ return { glob: match };
+ if (isRegExp(match))
+ return { regexSource: match.source, regexFlags: match.flags };
+ if (isURLPattern(match))
+ return { urlPattern: serializeURLPattern(match) };
+ // Functions cannot be serialized
+ return undefined;
+}
+
+function deserializeURLPattern(v: ReturnType<typeof serializeURLPattern>): URLPattern | ((url: URL) => boolean) {
+ // Client is on Node 24+ and can use URLPattern, Server is not. Let's match all URLs on the server, they'll be filtered again on the client.
+ // @ts-expect-error URLPattern is not in @types/node yet
+ // eslint-disable-next-line no-restricted-globals
+ if (typeof globalThis.URLPattern !== 'function')
+ return () => true;
+
+ // @ts-expect-error URLPattern is not in @types/node yet
+ // eslint-disable-next-line no-restricted-globals
+ return new globalThis.URLPattern({
+ hash: v.hash,
+ hostname: v.hostname,
+ password: v.password,
+ pathname: v.pathname,
+ port: v.port,
+ protocol: v.protocol,
+ search: v.search,
+ username: v.username,
+ });
+}
+
+export function deserializeURLMatch(match: { glob?: string, regexSource?: string, regexFlags?: string, urlPattern?: ReturnType<typeof serializeURLPattern> }): URLMatch {
+ if (match.regexSource)
+ return new RegExp(match.regexSource, match.regexFlags);
+ if (match.urlPattern)
+ return deserializeURLPattern(match.urlPattern);
+ return match.glob!;
+}
export function urlMatchesEqual(match1: URLMatch, match2: URLMatch) {
if (isRegExp(match1) && isRegExp(match2))
@@ -102,8 +173,10 @@ export function urlMatches(baseURL: string | undefined, urlString: string, match
const url = parseURL(urlString);
if (!url)
return false;
+ if (isURLPattern(match))
+ return match.test(url.href);
if (typeof match !== 'function')
- throw new Error('url parameter should be string, RegExp or function');
+ throw new Error('url parameter should be string, RegExp, URLPattern or function');
return match(url);
}
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index f174c4344d..add5421430 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -20,6 +20,10 @@ import { ReadStream } from 'fs';
import { Protocol } from './protocol';
import { Serializable, EvaluationArgument, PageFunction, PageFunctionOn, SmartHandle, ElementHandleForTag, BindingSource } from './structs';
+// Use the global URLPattern type if available (Node.js 22+, modern browsers),
+// otherwise fall back to `never` so it disappears from union types.
+type URLPattern = typeof globalThis extends { URLPattern: infer T } ? T : never;
+
type PageWaitForSelectorOptionsNotHidden = PageWaitForSelectorOptions & {
state?: 'visible'|'attached';
};
@@ -2840,9 +2844,9 @@ export interface Page {
name?: string;
/**
- * A glob pattern, regex pattern or predicate receiving frame's `url` as a [URL] object. Optional.
+ * A glob pattern, regex pattern, URL pattern, or predicate receiving frame's `url` as a [URL] object. Optional.
*/
- url?: string|RegExp|((url: URL) => boolean);
+ url?: string|RegExp|URLPattern|((url: URL) => boolean);
}): null|Frame;
/**
@@ -4097,14 +4101,14 @@ export interface Page {
*
* **NOTE** Enabling routing disables http cache.
*
- * @param url A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate that receives a [URL] to match during routing. If
* [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) is set in the
* context options and the provided URL is a string that does not start with `*`, it is resolved using the
* [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
* @param handler handler function to route the request.
* @param options
*/
- route(url: string|RegExp|((url: URL) => boolean), handler: ((route: Route, request: Request) => Promise<any>|any), options?: {
+ route(url: string|RegExp|URLPattern|((url: URL) => boolean), handler: ((route: Route, request: Request) => Promise<any>|any), options?: {
/**
* How often a route should be used. By default it will be used every time.
*/
@@ -4185,7 +4189,7 @@ export interface Page {
* [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) context option.
* @param handler Handler function to route the WebSocket.
*/
- routeWebSocket(url: string|RegExp|((url: URL) => boolean), handler: ((websocketroute: WebSocketRoute) => Promise<any>|any)): Promise<void>;
+ routeWebSocket(url: string|RegExp|URLPattern|((url: URL) => boolean), handler: ((websocketroute: WebSocketRoute) => Promise<any>|any)): Promise<void>;
/**
* Returns the buffer with the captured screenshot.
@@ -4776,10 +4780,10 @@ export interface Page {
* [page.route(url, handler[, options])](https://playwright.dev/docs/api/class-page#page-route). When
* [`handler`](https://playwright.dev/docs/api/class-page#page-unroute-option-handler) is not specified, removes all
* routes for the [`url`](https://playwright.dev/docs/api/class-page#page-unroute-option-url).
- * @param url A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while routing.
* @param handler Optional handler function to route the request.
*/
- unroute(url: string|RegExp|((url: URL) => boolean), handler?: ((route: Route, request: Request) => Promise<any>|any)): Promise<void>;
+ unroute(url: string|RegExp|URLPattern|((url: URL) => boolean), handler?: ((route: Route, request: Request) => Promise<any>|any)): Promise<void>;
/**
* Removes all routes created with
@@ -5111,11 +5115,11 @@ export interface Page {
timeout?: number;
/**
- * A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- * the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- * equal to the string.
+ * A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while waiting for the navigation.
+ * Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that
+ * is exactly equal to the string.
*/
- url?: string|RegExp|((url: URL) => boolean);
+ url?: string|RegExp|URLPattern|((url: URL) => boolean);
/**
* When to consider operation succeeded, defaults to `load`. Events can be either:
@@ -5229,12 +5233,12 @@ export interface Page {
* await page.waitForURL('**\/target.html');
* ```
*
- * @param url A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- * the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- * equal to the string.
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while waiting for the navigation.
+ * Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that
+ * is exactly equal to the string.
* @param options
*/
- waitForURL(url: string|RegExp|((url: URL) => boolean), options?: {
+ waitForURL(url: string|RegExp|URLPattern|((url: URL) => boolean), options?: {
/**
* Maximum operation time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via
* `navigationTimeout` option in the config, or by using the
@@ -8294,11 +8298,11 @@ export interface Frame {
timeout?: number;
/**
- * A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- * the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- * equal to the string.
+ * A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while waiting for the navigation.
+ * Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that
+ * is exactly equal to the string.
*/
- url?: string|RegExp|((url: URL) => boolean);
+ url?: string|RegExp|URLPattern|((url: URL) => boolean);
/**
* When to consider operation succeeded, defaults to `load`. Events can be either:
@@ -8335,12 +8339,12 @@ export interface Frame {
* await frame.waitForURL('**\/target.html');
* ```
*
- * @param url A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if
- * the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly
- * equal to the string.
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] to match while waiting for the navigation.
+ * Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that
+ * is exactly equal to the string.
* @param options
*/
- waitForURL(url: string|RegExp|((url: URL) => boolean), options?: {
+ waitForURL(url: string|RegExp|URLPattern|((url: URL) => boolean), options?: {
/**
* Maximum operation time in milliseconds. Defaults to `0` - no timeout. The default value can be changed via
* `navigationTimeout` option in the config, or by using the
@@ -9418,14 +9422,14 @@ export interface BrowserContext {
*
* **NOTE** Enabling routing disables http cache.
*
- * @param url A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate that receives a [URL] to match during routing. If
* [`baseURL`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-base-url) is set in the
* context options and the provided URL is a string that does not start with `*`, it is resolved using the
* [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
* @param handler handler function to route the request.
* @param options
*/
- route(url: string|RegExp|((url: URL) => boolean), handler: ((route: Route, request: Request) => Promise<any>|any), options?: {
+ route(url: string|RegExp|URLPattern|((url: URL) => boolean), handler: ((route: Route, request: Request) => Promise<any>|any), options?: {
/**
* How often a route should be used. By default it will be used every time.
*/
@@ -9738,12 +9742,12 @@ export interface BrowserContext {
* When [`handler`](https://playwright.dev/docs/api/class-browsercontext#browser-context-unroute-option-handler) is
* not specified, removes all routes for the
* [`url`](https://playwright.dev/docs/api/class-browsercontext#browser-context-unroute-option-url).
- * @param url A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with
+ * @param url A glob pattern, regex pattern, URL pattern, or predicate receiving [URL] used to register a routing with
* [browserContext.route(url, handler[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-route).
* @param handler Optional handler function used to register a routing with
* [browserContext.route(url, handler[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-route).
*/
- unroute(url: string|RegExp|((url: URL) => boolean), handler?: ((route: Route, request: Request) => Promise<any>|any)): Promise<void>;
+ unroute(url: string|RegExp|URLPattern|((url: URL) => boolean), handler?: ((route: Route, request: Request) => Promise<any>|any)): Promise<void>;
/**
* Removes all routes created with
diff --git a/packages/playwright/src/matchers/matchers.ts b/packages/playwright/src/matchers/matchers.ts
index f1f1e784a4..d59c9681ac 100644
--- a/packages/playwright/src/matchers/matchers.ts
+++ b/packages/playwright/src/matchers/matchers.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { asLocatorDescription, constructURLBasedOnBaseURL, isRegExp, isString, isTextualMimeType, pollAgainstDeadline, serializeExpectedTextValues, formatMatcherMessage } from 'playwright-core/lib/utils';
+import { asLocatorDescription, constructURLBasedOnBaseURL, isRegExp, isString, isTextualMimeType, isURLPattern, pollAgainstDeadline, serializeExpectedTextValues, formatMatcherMessage } from 'playwright-core/lib/utils';
import { colors } from 'playwright-core/lib/utils';
import { expectTypes } from '../util';
@@ -33,7 +33,7 @@ import type { TestStepInfoImpl } from '../worker/testInfo';
import type { APIResponse, Locator, Frame, Page } from 'playwright-core';
import type { FrameExpectParams } from 'playwright-core/lib/client/types';
import type { ExpectMatcherUtils } from '../../types/test';
-import type { InternalMatcherUtils } from 'playwright-core/lib/utils';
+import type { InternalMatcherUtils, URLPattern } from 'playwright-core/lib/utils';
export type ExpectMatcherStateInternal = Omit<ExpectMatcherState, 'utils'> & {
_stepInfo?: TestStepInfoImpl;
@@ -435,9 +435,12 @@ export function toHaveTitle(
export function toHaveURL(
this: ExpectMatcherStateInternal,
page: Page,
- expected: string | RegExp | ((url: URL) => boolean),
+ expected: string | RegExp | URLPattern | ((url: URL) => boolean),
options?: { ignoreCase?: boolean; timeout?: number },
) {
+ if (isURLPattern(expected))
+ return toHaveURLWithPredicate.call(this, page, url => (expected as URLPattern).test(url.href), options);
+
// Ports don't support predicates. Keep separate server and client codepaths
if (typeof expected === 'function')
return toHaveURLWithPredicate.call(this, page, expected, options);
diff --git a/packages/playwright/types/test.d.ts b/packages/playwright/types/test.d.ts
index 011941effe..0da905e6e3 100644
--- a/packages/playwright/types/test.d.ts
+++ b/packages/playwright/types/test.d.ts
@@ -7734,6 +7734,9 @@ type CustomProperties<T> = ExcludeProps<T, PlaywrightTestOptions & PlaywrightWor
export type PlaywrightTestProject<TestArgs = {}, WorkerArgs = {}> = Project<PlaywrightTestOptions & CustomProperties<TestArgs>, PlaywrightWorkerOptions & CustomProperties<WorkerArgs>>;
export type PlaywrightTestConfig<TestArgs = {}, WorkerArgs = {}> = Config<PlaywrightTestOptions & CustomProperties<TestArgs>, PlaywrightWorkerOptions & CustomProperties<WorkerArgs>>;
+// Use the global URLPattern type if available (Node.js 22+, modern browsers),
+// otherwise fall back to `never` so it disappears from union types.
+type URLPattern = typeof globalThis extends { URLPattern: infer T } ? T : never;
type AsymmetricMatcher = Record<string, any>;
interface AsymmetricMatchers {
@@ -9719,6 +9722,9 @@ interface PageAssertions {
* // Check for the page URL to contain 'doc', followed by an optional 's', followed by '/'
* await expect(page).toHaveURL(/docs?\//);
*
+ * // Check for the page URL to match the URL pattern
+ * await expect(page).toHaveURL(new URLPattern({ pathname: '/docs/*' }));
+ *
* // Check for the predicate to be satisfied
* // For example: verify query strings
* await expect(page).toHaveURL(url => {
@@ -9734,7 +9740,7 @@ interface PageAssertions {
* against the current browser URL.
* @param options
*/
- toHaveURL(url: string|RegExp|((url: URL) => boolean), options?: {
+ toHaveURL(url: string|RegExp|URLPattern|((url: URL) => boolean), options?: {
/**
* Whether to perform case-insensitive match.
* [`ignoreCase`](https://playwright.dev/docs/api/class-pageassertions#page-assertions-to-have-url-option-ignore-case)
diff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.ts
index 395a252733..595177f745 100644
--- a/packages/protocol/src/channels.d.ts
+++ b/packages/protocol/src/channels.d.ts
@@ -224,6 +224,17 @@ export type SelectorEngine = {
contentScript?: boolean,
};
+export type URLPattern = {
+ hash: string,
+ hostname: string,
+ password: string,
+ pathname: string,
+ port: string,
+ protocol: string,
+ search: string,
+ username: string,
+};
+
export type SetNetworkCookie = {
name: string,
value: string,
@@ -1812,6 +1823,7 @@ export type BrowserContextSetNetworkInterceptionPatternsParams = {
glob?: string,
regexSource?: string,
regexFlags?: string,
+ urlPattern?: URLPattern,
}[],
};
export type BrowserContextSetNetworkInterceptionPatternsOptions = {
@@ -1823,6 +1835,7 @@ export type BrowserContextSetWebSocketInterceptionPatternsParams = {
glob?: string,
regexSource?: string,
regexFlags?: string,
+ urlPattern?: URLPattern,
}[],
};
export type BrowserContextSetWebSocketInterceptionPatternsOptions = {
@@ -2355,6 +2368,7 @@ export type PageSetNetworkInterceptionPatternsParams = {
glob?: string,
regexSource?: string,
regexFlags?: string,
+ urlPattern?: URLPattern,
}[],
};
export type PageSetNetworkInterceptionPatternsOptions = {
@@ -2366,6 +2380,7 @@ export type PageSetWebSocketInterceptionPatternsParams = {
glob?: string,
regexSource?: string,
regexFlags?: string,
+ urlPattern?: URLPattern,
}[],
};
export type PageSetWebSocketInterceptionPatternsOptions = {
diff --git a/packages/protocol/src/protocol.yml b/packages/protocol/src/protocol.yml
index 67428bf8d4..e0da82b597 100644
--- a/packages/protocol/src/protocol.yml
+++ b/packages/protocol/src/protocol.yml
@@ -161,6 +161,17 @@ SelectorEngine:
source: string
contentScript: boolean?
+URLPattern:
+ type: object
+ properties:
+ hash: string
+ hostname: string
+ password: string
+ pathname: string
+ port: string
+ protocol: string
+ search: string
+ username: string
SetNetworkCookie:
type: object
@@ -1279,6 +1290,7 @@ BrowserContext:
glob: string?
regexSource: string?
regexFlags: string?
+ urlPattern: URLPattern?
setWebSocketInterceptionPatterns:
title: Route WebSockets
@@ -1292,6 +1304,7 @@ BrowserContext:
glob: string?
regexSource: string?
regexFlags: string?
+ urlPattern: URLPattern?
setOffline:
title: Set offline mode
@@ -1747,6 +1760,7 @@ Page:
glob: string?
regexSource: string?
regexFlags: string?
+ urlPattern: URLPattern?
setWebSocketInterceptionPatterns:
title: Route WebSockets
@@ -1760,6 +1774,7 @@ Page:
glob: string?
regexSource: string?
regexFlags: string?
+ urlPattern: URLPattern?
setViewportSize:
title: Set viewport size
diff --git a/tests/page/expect-misc.spec.ts b/tests/page/expect-misc.spec.ts
index c5615c8514..34edb029b4 100644
--- a/tests/page/expect-misc.spec.ts
+++ b/tests/page/expect-misc.spec.ts
@@ -410,6 +410,15 @@ Timeout: 10000ms
await page.goto('data:text/html,<div>A</div>');
await expect(page).toHaveURL('DATA:teXT/HTml,<div>a</div>', { ignoreCase: true });
});
+
+ test('support URLPattern', async ({ page }) => {
+ test.skip(globalThis.URLPattern === undefined, 'URLPattern is not supported in this environment');
+ await page.goto('data:text/html,<div>A</div>');
+ // @ts-ignore URLPattern is not in @types/node yet
+ await expect(page).toHaveURL(new URLPattern({ protocol: 'data' }));
+ // @ts-ignore
+ await expect(page).not.toHaveURL(new URLPattern({ protocol: 'http' }));
+ });
});
test.describe('toHaveAttribute', () => {
diff --git a/utils/generate_types/overrides-test.d.ts b/utils/generate_types/overrides-test.d.ts
index bfcac9586a..4d0f95de9f 100644
--- a/utils/generate_types/overrides-test.d.ts
+++ b/utils/generate_types/overrides-test.d.ts
@@ -335,6 +335,9 @@ type CustomProperties<T> = ExcludeProps<T, PlaywrightTestOptions & PlaywrightWor
export type PlaywrightTestProject<TestArgs = {}, WorkerArgs = {}> = Project<PlaywrightTestOptions & CustomProperties<TestArgs>, PlaywrightWorkerOptions & CustomProperties<WorkerArgs>>;
export type PlaywrightTestConfig<TestArgs = {}, WorkerArgs = {}> = Config<PlaywrightTestOptions & CustomProperties<TestArgs>, PlaywrightWorkerOptions & CustomProperties<WorkerArgs>>;
+// Use the global URLPattern type if available (Node.js 22+, modern browsers),
+// otherwise fall back to `never` so it disappears from union types.
+type URLPattern = typeof globalThis extends { URLPattern: infer T } ? T : never;
type AsymmetricMatcher = Record<string, any>;
interface AsymmetricMatchers {
diff --git a/utils/generate_types/overrides.d.ts b/utils/generate_types/overrides.d.ts
index 09b54a6dd7..07a961d769 100644
--- a/utils/generate_types/overrides.d.ts
+++ b/utils/generate_types/overrides.d.ts
@@ -19,6 +19,10 @@ import { ReadStream } from 'fs';
import { Protocol } from './protocol';
import { Serializable, EvaluationArgument, PageFunction, PageFunctionOn, SmartHandle, ElementHandleForTag, BindingSource } from './structs';
+// Use the global URLPattern type if available (Node.js 22+, modern browsers),
+// otherwise fall back to `never` so it disappears from union types.
+type URLPattern = typeof globalThis extends { URLPattern: infer T } ? T : never;
+
type PageWaitForSelectorOptionsNotHidden = PageWaitForSelectorOptions & {
state?: 'visible'|'attached';
};