Class: Playwright::BrowserContext
- Inherits:
-
PlaywrightApi
- Object
- PlaywrightApi
- Playwright::BrowserContext
- Defined in:
- lib/playwright_api/browser_context.rb
Overview
-
extends: [EventEmitter]
BrowserContexts provide a way to operate multiple independent browser sessions.
If a page opens another page, e.g. with a ‘window.open` call, the popup will belong to the parent page’s browser context.
Playwright allows creating “incognito” browser contexts with [‘method: Browser.newContext`] method. “Incognito” browser contexts don’t write any browsing data to disk.
“‘python sync # create a new incognito browser context context = browser.new_context() # create a new page inside context. page = context.new_page() page.goto(“example.com”) # dispose context once it is no longer needed. context.close() “`
Instance Method Summary collapse
-
#add_cookies(cookies) ⇒ Object
Adds cookies into this browser context.
-
#add_init_script(path: nil, script: nil) ⇒ Object
Adds a script which would be evaluated in one of the following scenarios: - Whenever a page is created in the browser context or is navigated.
-
#background_pages ⇒ Object
NOTE: Background pages are only supported on Chromium-based browsers.
-
#browser ⇒ Object
Returns the browser instance of the context.
- #browser=(req) ⇒ Object
-
#clear_cookies(domain: nil, name: nil, path: nil) ⇒ Object
Removes cookies from context.
-
#clear_permissions ⇒ Object
Clears all permission overrides for the browser context.
-
#clock ⇒ Object
Playwright has ability to mock clock and passage of time.
-
#close(reason: nil) ⇒ Object
Closes the browser context.
-
#cookies(urls: nil) ⇒ Object
If no URLs are specified, this method returns all cookies.
- #enable_debug_console! ⇒ Object
-
#expect_console_message(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a ‘ConsoleMessage` to be logged by in the pages in the context.
-
#expect_event(event, predicate: nil, timeout: nil, &block) ⇒ Object
Waits for event to fire and passes its value into the predicate function.
-
#expect_page(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a new ‘Page` to be created in the context.
-
#expose_binding(name, callback, handle: nil) ⇒ Object
The method adds a function called ‘name` on the `window` object of every frame in every page in the context.
-
#expose_function(name, callback) ⇒ Object
The method adds a function called ‘name` on the `window` object of every frame in every page in the context.
-
#grant_permissions(permissions, origin: nil) ⇒ Object
Grants specified permissions to the browser context.
-
#new_cdp_session(page) ⇒ Object
NOTE: CDP sessions are only supported on Chromium-based browsers.
-
#new_page(&block) ⇒ Object
Creates a new page in the browser context.
-
#off(event, callback) ⇒ Object
– inherited from EventEmitter –.
-
#on(event, callback) ⇒ Object
– inherited from EventEmitter –.
-
#once(event, callback) ⇒ Object
– inherited from EventEmitter –.
- #options=(req) ⇒ Object
- #owner_page=(req) ⇒ Object
-
#pages ⇒ Object
Returns all open pages in the context.
- #pause ⇒ Object
-
#request ⇒ Object
API testing helper associated with this context.
-
#route(url, handler, times: nil) ⇒ Object
Routing provides the capability to modify network requests that are made by any page in the browser context.
-
#route_from_har(har, notFound: nil, update: nil, updateContent: nil, updateMode: nil, url: nil) ⇒ Object
If specified the network requests that are made in the context will be served from the HAR file.
-
#service_workers ⇒ Object
NOTE: Service workers are only supported on Chromium-based browsers.
-
#set_default_navigation_timeout(timeout) ⇒ Object
(also: #default_navigation_timeout=)
This setting will change the default maximum navigation time for the following methods and related shortcuts: - [‘method: Page.goBack`] - [`method: Page.goForward`] - [`method: Page.goto`] - [`method: Page.reload`] - [`method: Page.setContent`] - [`method: Page.waitForNavigation`].
-
#set_default_timeout(timeout) ⇒ Object
(also: #default_timeout=)
This setting will change the default maximum time for all the methods accepting ‘timeout` option.
-
#set_extra_http_headers(headers) ⇒ Object
(also: #extra_http_headers=)
The extra HTTP headers will be sent with every request initiated by any page in the context.
-
#set_geolocation(geolocation) ⇒ Object
(also: #geolocation=)
Sets the context’s geolocation.
- #set_offline(offline) ⇒ Object (also: #offline=)
-
#storage_state(path: nil) ⇒ Object
Returns storage state for this browser context, contains current cookies and local storage snapshot.
-
#tracing ⇒ Object
property.
-
#unroute(url, handler: nil) ⇒ Object
Removes a route created with [‘method: BrowserContext.route`].
-
#unroute_all(behavior: nil) ⇒ Object
Removes all routes created with [‘method: BrowserContext.route`] and [`method: BrowserContext.routeFromHAR`].
-
#wait_for_event(event, predicate: nil, timeout: nil) ⇒ Object
NOTE: In most cases, you should use [‘method: BrowserContext.waitForEvent`].
Methods inherited from PlaywrightApi
Constructor Details
This class inherits a constructor from Playwright::PlaywrightApi
Instance Method Details
#add_cookies(cookies) ⇒ Object
Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via [‘method: BrowserContext.cookies`].
Usage
“‘python sync browser_context.add_cookies([cookie_object1, cookie_object2]) “`
48 49 50 |
# File 'lib/playwright_api/browser_context.rb', line 48 def () wrap_impl(@impl.(unwrap_impl())) end |
#add_init_script(path: nil, script: nil) ⇒ Object
Adds a script which would be evaluated in one of the following scenarios:
-
Whenever a page is created in the browser context or is navigated.
-
Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed ‘Math.random`.
Usage
An example of overriding ‘Math.random` before the page loads:
“‘python sync # in your playwright script, assuming the preload.js file is in same directory. browser_context.add_init_script(path=“preload.js”) “`
NOTE: The order of evaluation of multiple scripts installed via [‘method: BrowserContext.addInitScript`] and
- ‘method: Page.addInitScript`
-
is not defined.
71 72 73 |
# File 'lib/playwright_api/browser_context.rb', line 71 def add_init_script(path: nil, script: nil) wrap_impl(@impl.add_init_script(path: unwrap_impl(path), script: unwrap_impl(script))) end |
#background_pages ⇒ Object
NOTE: Background pages are only supported on Chromium-based browsers.
All existing background pages in the context.
79 80 81 |
# File 'lib/playwright_api/browser_context.rb', line 79 def background_pages wrap_impl(@impl.background_pages) end |
#browser ⇒ Object
Returns the browser instance of the context. If it was launched as a persistent context null gets returned.
85 86 87 |
# File 'lib/playwright_api/browser_context.rb', line 85 def browser wrap_impl(@impl.browser) end |
#browser=(req) ⇒ Object
462 463 464 |
# File 'lib/playwright_api/browser_context.rb', line 462 def browser=(req) wrap_impl(@impl.browser=(unwrap_impl(req))) end |
#clear_cookies(domain: nil, name: nil, path: nil) ⇒ Object
Removes cookies from context. Accepts optional filter.
Usage
“‘python sync context.clear_cookies() context.clear_cookies(name=“session-id”) context.clear_cookies(domain=“my-origin.com”) context.clear_cookies(path=“/api/v1”) context.clear_cookies(name=“session-id”, domain=“my-origin.com”) “`
101 102 103 |
# File 'lib/playwright_api/browser_context.rb', line 101 def (domain: nil, name: nil, path: nil) wrap_impl(@impl.(domain: unwrap_impl(domain), name: unwrap_impl(name), path: unwrap_impl(path))) end |
#clear_permissions ⇒ Object
Clears all permission overrides for the browser context.
Usage
“‘python sync context = browser.new_context() context.grant_permissions() # do stuff .. context.clear_permissions() “`
116 117 118 |
# File 'lib/playwright_api/browser_context.rb', line 116 def wrap_impl(@impl.) end |
#clock ⇒ Object
Playwright has ability to mock clock and passage of time.
25 26 27 |
# File 'lib/playwright_api/browser_context.rb', line 25 def clock # property wrap_impl(@impl.clock) end |
#close(reason: nil) ⇒ Object
Closes the browser context. All the pages that belong to the browser context will be closed.
NOTE: The default browser context cannot be closed.
124 125 126 |
# File 'lib/playwright_api/browser_context.rb', line 124 def close(reason: nil) wrap_impl(@impl.close(reason: unwrap_impl(reason))) end |
#cookies(urls: nil) ⇒ Object
If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.
131 132 133 |
# File 'lib/playwright_api/browser_context.rb', line 131 def (urls: nil) wrap_impl(@impl.(urls: unwrap_impl(urls))) end |
#enable_debug_console! ⇒ Object
457 458 459 |
# File 'lib/playwright_api/browser_context.rb', line 457 def enable_debug_console! wrap_impl(@impl.enable_debug_console!) end |
#expect_console_message(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a ‘ConsoleMessage` to be logged by in the pages in the context. If predicate is provided, it passes `ConsoleMessage` value into the `predicate` function and waits for `predicate(message)` to return a truthy value. Will throw an error if the page is closed before the [`event: BrowserContext.console`] event is fired.
404 405 406 |
# File 'lib/playwright_api/browser_context.rb', line 404 def (predicate: nil, timeout: nil, &block) wrap_impl(@impl.(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end |
#expect_event(event, predicate: nil, timeout: nil, &block) ⇒ Object
Waits for event to fire and passes its value into the predicate function. Returns when the predicate returns truthy value. Will throw an error if the context closes before the event is fired. Returns the event data value.
Usage
“‘python sync with context.expect_event(“page”) as event_info:
page.get_by_role("button").click()
page = event_info.value “‘
419 420 421 |
# File 'lib/playwright_api/browser_context.rb', line 419 def expect_event(event, predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_event(unwrap_impl(event), predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end |
#expect_page(predicate: nil, timeout: nil, &block) ⇒ Object
Performs action and waits for a new ‘Page` to be created in the context. If predicate is provided, it passes `Page` value into the `predicate` function and waits for `predicate(event)` to return a truthy value. Will throw an error if the context closes before new `Page` is created.
427 428 429 |
# File 'lib/playwright_api/browser_context.rb', line 427 def expect_page(predicate: nil, timeout: nil, &block) wrap_impl(@impl.expect_page(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block))) end |
#expose_binding(name, callback, handle: nil) ⇒ Object
The method adds a function called ‘name` on the `window` object of every frame in every page in the context. When called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`. If the `callback` returns a [Promise], it will be awaited.
The first argument of the ‘callback` function contains information about the caller: `{ browserContext: BrowserContext, page: Page, frame: Frame }`.
See [‘method: Page.exposeBinding`] for page-only version.
Usage
An example of exposing page URL to all frames in all pages in the context:
“‘python sync from playwright.sync_api import sync_playwright, Playwright
def run(playwright: Playwright):
webkit = playwright.webkit
browser = webkit.launch(headless=False)
context = browser.new_context()
context.expose_binding("pageURL", lambda source: source["page"].url)
page = context.new_page()
page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
page.get_by_role("button").click()
with sync_playwright() as playwright:
run(playwright)
“‘
172 173 174 |
# File 'lib/playwright_api/browser_context.rb', line 172 def expose_binding(name, callback, handle: nil) wrap_impl(@impl.expose_binding(unwrap_impl(name), unwrap_impl(callback), handle: unwrap_impl(handle))) end |
#expose_function(name, callback) ⇒ Object
The method adds a function called ‘name` on the `window` object of every frame in every page in the context. When called, the function executes `callback` and returns a [Promise] which resolves to the return value of `callback`.
If the ‘callback` returns a [Promise], it will be awaited.
See [‘method: Page.exposeFunction`] for page-only version.
Usage
An example of adding a ‘sha256` function to all pages in the context:
“‘python sync import hashlib from playwright.sync_api import sync_playwright
def sha256(text: str) -> str:
m = hashlib.sha256()
m.update(bytes(text, "utf8"))
return m.hexdigest()
def run(playwright: Playwright):
webkit = playwright.webkit
browser = webkit.launch(headless=False)
context = browser.new_context()
context.expose_function("sha256", sha256)
page = context.new_page()
page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
page.get_by_role("button").click()
with sync_playwright() as playwright:
run(playwright)
“‘
219 220 221 |
# File 'lib/playwright_api/browser_context.rb', line 219 def expose_function(name, callback) wrap_impl(@impl.expose_function(unwrap_impl(name), unwrap_impl(callback))) end |
#grant_permissions(permissions, origin: nil) ⇒ Object
Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.
226 227 228 |
# File 'lib/playwright_api/browser_context.rb', line 226 def (, origin: nil) wrap_impl(@impl.(unwrap_impl(), origin: unwrap_impl(origin))) end |
#new_cdp_session(page) ⇒ Object
NOTE: CDP sessions are only supported on Chromium-based browsers.
Returns the newly created session.
234 235 236 |
# File 'lib/playwright_api/browser_context.rb', line 234 def new_cdp_session(page) wrap_impl(@impl.new_cdp_session(unwrap_impl(page))) end |
#new_page(&block) ⇒ Object
Creates a new page in the browser context.
240 241 242 |
# File 'lib/playwright_api/browser_context.rb', line 240 def new_page(&block) wrap_impl(@impl.new_page(&wrap_block_call(block))) end |
#off(event, callback) ⇒ Object
– inherited from EventEmitter –
480 481 482 |
# File 'lib/playwright_api/browser_context.rb', line 480 def off(event, callback) event_emitter_proxy.off(event, callback) end |
#on(event, callback) ⇒ Object
– inherited from EventEmitter –
474 475 476 |
# File 'lib/playwright_api/browser_context.rb', line 474 def on(event, callback) event_emitter_proxy.on(event, callback) end |
#once(event, callback) ⇒ Object
– inherited from EventEmitter –
468 469 470 |
# File 'lib/playwright_api/browser_context.rb', line 468 def once(event, callback) event_emitter_proxy.once(event, callback) end |
#options=(req) ⇒ Object
452 453 454 |
# File 'lib/playwright_api/browser_context.rb', line 452 def (req) wrap_impl(@impl.=(unwrap_impl(req))) end |
#owner_page=(req) ⇒ Object
447 448 449 |
# File 'lib/playwright_api/browser_context.rb', line 447 def owner_page=(req) wrap_impl(@impl.owner_page=(unwrap_impl(req))) end |
#pages ⇒ Object
Returns all open pages in the context.
246 247 248 |
# File 'lib/playwright_api/browser_context.rb', line 246 def pages wrap_impl(@impl.pages) end |
#pause ⇒ Object
442 443 444 |
# File 'lib/playwright_api/browser_context.rb', line 442 def pause wrap_impl(@impl.pause) end |
#request ⇒ Object
API testing helper associated with this context. Requests made with this API will use context cookies.
31 32 33 |
# File 'lib/playwright_api/browser_context.rb', line 31 def request # property wrap_impl(@impl.request) end |
#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 `Browser.newContext.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.
297 298 299 |
# File 'lib/playwright_api/browser_context.rb', line 297 def route(url, handler, times: nil) wrap_impl(@impl.route(unwrap_impl(url), unwrap_impl(handler), times: unwrap_impl(times))) end |
#route_from_har(har, notFound: nil, update: nil, updateContent: nil, updateMode: nil, url: nil) ⇒ Object
If specified the network requests that are made in the context will be served from the HAR file. Read more about [Replaying from HAR](../mock.md#replaying-from-har).
Playwright will not serve requests intercepted by Service Worker from the HAR file. See [this](github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when using request interception by setting ‘Browser.newContext.serviceWorkers` to `’block’‘.
305 306 307 308 309 310 311 312 313 |
# File 'lib/playwright_api/browser_context.rb', line 305 def route_from_har( har, notFound: nil, update: nil, updateContent: nil, updateMode: nil, url: nil) wrap_impl(@impl.route_from_har(unwrap_impl(har), notFound: unwrap_impl(notFound), update: unwrap_impl(update), updateContent: unwrap_impl(updateContent), updateMode: unwrap_impl(updateMode), url: unwrap_impl(url))) end |
#service_workers ⇒ Object
NOTE: Service workers are only supported on Chromium-based browsers.
All existing service workers in the context.
319 320 321 |
# File 'lib/playwright_api/browser_context.rb', line 319 def service_workers wrap_impl(@impl.service_workers) end |
#set_default_navigation_timeout(timeout) ⇒ Object Also known as:
This setting will change the default maximum navigation time for the following methods and related shortcuts:
- ‘method: Page.goBack`
- ‘method: Page.goForward`
- ‘method: Page.goto`
- ‘method: Page.reload`
- ‘method: Page.setContent`
- ‘method: Page.waitForNavigation`
NOTE: [‘method: Page.setDefaultNavigationTimeout`] and [`method: Page.setDefaultTimeout`] take priority over [`method: BrowserContext.setDefaultNavigationTimeout`].
334 335 336 |
# File 'lib/playwright_api/browser_context.rb', line 334 def (timeout) wrap_impl(@impl.(unwrap_impl(timeout))) end |
#set_default_timeout(timeout) ⇒ Object Also known as: default_timeout=
This setting will change the default maximum time for all the methods accepting ‘timeout` option.
NOTE: [‘method: Page.setDefaultNavigationTimeout`], [`method: Page.setDefaultTimeout`] and
- ‘method: BrowserContext.setDefaultNavigationTimeout`
-
take priority over [‘method: BrowserContext.setDefaultTimeout`].
344 345 346 |
# File 'lib/playwright_api/browser_context.rb', line 344 def set_default_timeout(timeout) wrap_impl(@impl.set_default_timeout(unwrap_impl(timeout))) end |
#set_extra_http_headers(headers) ⇒ Object Also known as: extra_http_headers=
The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set with [‘method: Page.setExtraHTTPHeaders`]. If page overrides a particular header, page-specific header value will be used instead of the browser context header value.
NOTE: [‘method: BrowserContext.setExtraHTTPHeaders`] does not guarantee the order of headers in the outgoing requests.
355 356 357 |
# File 'lib/playwright_api/browser_context.rb', line 355 def set_extra_http_headers(headers) wrap_impl(@impl.set_extra_http_headers(unwrap_impl(headers))) end |
#set_geolocation(geolocation) ⇒ Object Also known as: geolocation=
Sets the context’s geolocation. Passing ‘null` or `undefined` emulates position unavailable.
Usage
“‘python sync browser_context.set_geolocation(59.95, “longitude”: 30.31667) “`
NOTE: Consider using [‘method: BrowserContext.grantPermissions`] to grant permissions for the browser context pages to read its geolocation.
371 372 373 |
# File 'lib/playwright_api/browser_context.rb', line 371 def set_geolocation(geolocation) wrap_impl(@impl.set_geolocation(unwrap_impl(geolocation))) end |
#set_offline(offline) ⇒ Object Also known as: offline=
376 377 378 |
# File 'lib/playwright_api/browser_context.rb', line 376 def set_offline(offline) wrap_impl(@impl.set_offline(unwrap_impl(offline))) end |
#storage_state(path: nil) ⇒ Object
Returns storage state for this browser context, contains current cookies and local storage snapshot.
383 384 385 |
# File 'lib/playwright_api/browser_context.rb', line 383 def storage_state(path: nil) wrap_impl(@impl.storage_state(path: unwrap_impl(path))) end |
#tracing ⇒ Object
property
35 36 37 |
# File 'lib/playwright_api/browser_context.rb', line 35 def tracing # property wrap_impl(@impl.tracing) end |
#unroute(url, handler: nil) ⇒ Object
Removes a route created with [‘method: BrowserContext.route`]. When `handler` is not specified, removes all routes for the `url`.
396 397 398 |
# File 'lib/playwright_api/browser_context.rb', line 396 def unroute(url, handler: nil) wrap_impl(@impl.unroute(unwrap_impl(url), handler: unwrap_impl(handler))) end |
#unroute_all(behavior: nil) ⇒ Object
Removes all routes created with [‘method: BrowserContext.route`] and [`method: BrowserContext.routeFromHAR`].
389 390 391 |
# File 'lib/playwright_api/browser_context.rb', line 389 def unroute_all(behavior: nil) wrap_impl(@impl.unroute_all(behavior: unwrap_impl(behavior))) end |
#wait_for_event(event, predicate: nil, timeout: nil) ⇒ Object
NOTE: In most cases, you should use [‘method: BrowserContext.waitForEvent`].
Waits for given ‘event` to fire. If predicate is provided, it passes event’s value into the ‘predicate` function and waits for `predicate(event)` to return a truthy value. Will throw an error if the browser context is closed before the `event` is fired.
437 438 439 |
# File 'lib/playwright_api/browser_context.rb', line 437 def wait_for_event(event, predicate: nil, timeout: nil) raise NotImplementedError.new('wait_for_event is not implemented yet.') end |