Method: Playwright::BrowserContext#route
- Defined in:
- lib/playwright_api/browser_context.rb
#route(url, handler, times: nil) ⇒ Object
Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it’s continued, fulfilled or aborted.
NOTE: [‘method: BrowserContext.route`] will not intercept requests intercepted by Service Worker. See [this](github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting `serviceWorkers` to `’block’‘.
Usage
An example of a naive handler that aborts all image requests:
“‘python sync context = browser.new_context() page = context.new_page() context.route(“*/.png,jpg,jpeg”, lambda route: route.abort()) page.goto(“example.com”) browser.close() “`
or the same snippet using a regex pattern instead:
“‘python sync context = browser.new_context() page = context.new_page() context.route(re.compile(r“(.png$)|(.jpg$)”), lambda route: route.abort()) page = await context.new_page() page = context.new_page() page.goto(“example.com”) browser.close() “`
It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:
“‘python sync def handle_route(route: Route):
if ("my-string" in route.request.post_data):
route.fulfill(body="mocked-data")
else:
route.continue_()
context.route(“/api/**”, handle_route) “‘
Page routes (set up with [‘method: Page.route`]) take precedence over browser context routes when request matches both handlers.
To remove a route with its handler you can use [‘method: BrowserContext.unroute`].
NOTE: Enabling routing disables http cache.
296 297 298 |
# File 'lib/playwright_api/browser_context.rb', line 296 def route(url, handler, times: nil) wrap_impl(@impl.route(unwrap_impl(url), unwrap_impl(handler), times: unwrap_impl(times))) end |