Rayrun
← Back to Discord Forum

Intercept all URL using "*" on `page.route()` function

Playwright doesn't seem to intercept the requests unless I specify exactly the URL i want to block

const primaryStreamURL = await getElementById(page, "PrimaryStreamURL").evaluate(
            (el: HTMLInputElement) => el.value
        );
        if (!primaryStreamURL) throw new Error("Primary stream URL is empty");
        const primaryOrigin = new URL(primaryStreamURL).origin;
        await page.route(`${primaryOrigin}/*`, async (route) => {
            console.log(route.request().url()); // Never gets console logged
            await route.abort("connectionclosed");
        });

The URL is like this https://something.net/*. If I write it like this https://something.net/media.u3m8 it works. but there are another files that get downloaded and I need to intercept all of them, so adding a specific URL is not an option

This thread is trying to answer question "Why doesn't Playwright intercept requests with a wildcard '*' in 'page.route()' function and how can it be fixed?"

1 reply

Fixed it by using ${primaryOrigin}/**/* instead of ${primaryOrigin}/*

Answer

You can intercept all requests from a specific origin in Playwright using the wildcard '*' in the page.route() function. Here's how you can do it:

await page.route('https://ray.run/*', route => {
  // Your interception logic goes here
});

In this code, any request made to URLs starting with "https://ray.run/" will be intercepted. You can then define your own logic inside the route handler function to handle these intercepted requests.

For example, if you want to block all requests from that origin, you can use route.abort():

await page.route('https://ray.run/*', route => {
  route.abort();
});

Alternatively, if you want to modify or fulfill these intercepted requests, you can use route.fulfill() and provide a custom response:

await page.route('https://ray.run/*', route => {
  const customResponse = {
    status: 200,
    contentType: 'text/html',
    body: 'Intercepted response',
  };
  
  route.fulfill(customResponse);
});

In this case, any request made to URLs starting with "https://ray.run/" will receive a custom response with status code 200, content type 'text/html', and body containing 'Intercepted response'.

Remember, when defining routes using page.route(), they take precedence over routes defined at browser context level using browserContext.route(). If there are conflicting routes for a specific request URL, the one defined at page level will be used.

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].