class Playwright::BrowserContext

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 creation of “incognito” browser contexts with `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() “`

Public Instance Methods

add_cookies(cookies) click to toggle source

Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via [`method: BrowserContext.cookies`].

“`python sync browser_context.add_cookies([cookie_object1, cookie_object2]) “`

# File lib/playwright_api/browser_context.rb, line 33
def add_cookies(cookies)
  wrap_impl(@impl.add_cookies(unwrap_impl(cookies)))
end
add_init_script(path: nil, script: nil) click to toggle source

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`.

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.

# File lib/playwright_api/browser_context.rb, line 54
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() click to toggle source

> NOTE: Background pages are only supported on Chromium-based browsers.

All existing background pages in the context.

# File lib/playwright_api/browser_context.rb, line 61
def background_pages
  wrap_impl(@impl.background_pages)
end
browser() click to toggle source

Returns the browser instance of the context. If it was launched as a persistent context null gets returned.

# File lib/playwright_api/browser_context.rb, line 66
def browser
  wrap_impl(@impl.browser)
end
browser=(req) click to toggle source

@nodoc

# File lib/playwright_api/browser_context.rb, line 371
def browser=(req)
  wrap_impl(@impl.browser=(unwrap_impl(req)))
end
clear_cookies() click to toggle source

Clears context cookies.

# File lib/playwright_api/browser_context.rb, line 71
def clear_cookies
  wrap_impl(@impl.clear_cookies)
end
clear_permissions() click to toggle source

Clears all permission overrides for the browser context.

“`python sync context = browser.new_context() context.grant_permissions() # do stuff .. context.clear_permissions() “`

# File lib/playwright_api/browser_context.rb, line 83
def clear_permissions
  wrap_impl(@impl.clear_permissions)
end
close() click to toggle source

Closes the browser context. All the pages that belong to the browser context will be closed.

> NOTE: The default browser context cannot be closed.

# File lib/playwright_api/browser_context.rb, line 90
def close
  wrap_impl(@impl.close)
end
cookies(urls: nil) click to toggle source

If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.

# File lib/playwright_api/browser_context.rb, line 96
def cookies(urls: nil)
  wrap_impl(@impl.cookies(urls: unwrap_impl(urls)))
end
default_navigation_timeout=(timeout)
default_timeout=(timeout)
Alias for: set_default_timeout
enable_debug_console!() click to toggle source

@nodoc

# File lib/playwright_api/browser_context.rb, line 366
def enable_debug_console!
  wrap_impl(@impl.enable_debug_console!)
end
expect_event(event, predicate: nil, timeout: nil, &block) click to toggle source

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.

“`python sync with context.expect_event(“page”) as event_info:

page.click("button")

page = event_info.value “`

# File lib/playwright_api/browser_context.rb, line 345
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) click to toggle source

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.

# File lib/playwright_api/browser_context.rb, line 352
def expect_page(predicate: nil, timeout: nil)
  wrap_impl(@impl.expect_page(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout)))
end
expose_binding(name, callback, handle: nil) click to toggle source

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.

An example of exposing page URL to all frames in all pages in the context:

“`python sync from playwright.sync_api import sync_playwright

def run(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.click("button")

with sync_playwright() as playwright:

run(playwright)

“`

An example of passing an element handle:

“`python sync def print(source, element):

print(element.text_content())

context.expose_binding(“clicked”, print, handle=true) page.set_content(“”“

<script>
  document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>

“”“) “`

# File lib/playwright_api/browser_context.rb, line 150
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) click to toggle source

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.

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):

m = hashlib.sha256()
m.update(bytes(text, "utf8"))
return m.hexdigest()

def run(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.click("button")

with sync_playwright() as playwright:

run(playwright)

“`

# File lib/playwright_api/browser_context.rb, line 193
def expose_function(name, callback)
  wrap_impl(@impl.expose_function(unwrap_impl(name), unwrap_impl(callback)))
end
extra_http_headers=(headers)
geolocation=(geolocation)
Alias for: set_geolocation
grant_permissions(permissions, origin: nil) click to toggle source

Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.

# File lib/playwright_api/browser_context.rb, line 199
def grant_permissions(permissions, origin: nil)
  wrap_impl(@impl.grant_permissions(unwrap_impl(permissions), origin: unwrap_impl(origin)))
end
new_cdp_session(page) click to toggle source

> NOTE: CDP sessions are only supported on Chromium-based browsers.

Returns the newly created session.

# File lib/playwright_api/browser_context.rb, line 206
def new_cdp_session(page)
  wrap_impl(@impl.new_cdp_session(unwrap_impl(page)))
end
new_page(&block) click to toggle source

Creates a new page in the browser context.

# File lib/playwright_api/browser_context.rb, line 211
def new_page(&block)
  wrap_impl(@impl.new_page(&wrap_block_call(block)))
end
off(event, callback) click to toggle source

– inherited from EventEmitter – @nodoc

# File lib/playwright_api/browser_context.rb, line 404
def off(event, callback)
  event_emitter_proxy.off(event, callback)
end
offline=(offline)
Alias for: set_offline
on(event, callback) click to toggle source

– inherited from EventEmitter – @nodoc

# File lib/playwright_api/browser_context.rb, line 398
def on(event, callback)
  event_emitter_proxy.on(event, callback)
end
once(event, callback) click to toggle source

– inherited from EventEmitter – @nodoc

# File lib/playwright_api/browser_context.rb, line 392
def once(event, callback)
  event_emitter_proxy.once(event, callback)
end
options=(req) click to toggle source

@nodoc

# File lib/playwright_api/browser_context.rb, line 386
def options=(req)
  wrap_impl(@impl.options=(unwrap_impl(req)))
end
owner_page=(req) click to toggle source

@nodoc

# File lib/playwright_api/browser_context.rb, line 376
def owner_page=(req)
  wrap_impl(@impl.owner_page=(unwrap_impl(req)))
end
pages() click to toggle source

Returns all open pages in the context.

# File lib/playwright_api/browser_context.rb, line 216
def pages
  wrap_impl(@impl.pages)
end
pause() click to toggle source

@nodoc

# File lib/playwright_api/browser_context.rb, line 381
def pause
  wrap_impl(@impl.pause)
end
route(url, handler) click to toggle source

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.

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):

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.

# File lib/playwright_api/browser_context.rb, line 263
def route(url, handler)
  wrap_impl(@impl.route(unwrap_impl(url), unwrap_impl(handler)))
end
service_workers() click to toggle source

> NOTE: Service workers are only supported on Chromium-based browsers.

All existing service workers in the context.

# File lib/playwright_api/browser_context.rb, line 270
def service_workers
  wrap_impl(@impl.service_workers)
end
set_default_navigation_timeout(timeout) click to toggle source

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`].

# File lib/playwright_api/browser_context.rb, line 284
def set_default_navigation_timeout(timeout)
  wrap_impl(@impl.set_default_navigation_timeout(unwrap_impl(timeout)))
end
Also aliased as: default_navigation_timeout=
set_default_timeout(timeout) click to toggle source

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`].

# File lib/playwright_api/browser_context.rb, line 293
def set_default_timeout(timeout)
  wrap_impl(@impl.set_default_timeout(unwrap_impl(timeout)))
end
Also aliased as: default_timeout=
set_extra_http_headers(headers) click to toggle source

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.

# File lib/playwright_api/browser_context.rb, line 303
def set_extra_http_headers(headers)
  wrap_impl(@impl.set_extra_http_headers(unwrap_impl(headers)))
end
Also aliased as: extra_http_headers=
set_geolocation(geolocation) click to toggle source

Sets the context's geolocation. Passing `null` or `undefined` emulates position unavailable.

“`python sync browser_context.set_geolocation({“latitude”: 59.95, “longitude”: 30.31667}) “`

> NOTE: Consider using [`method: BrowserContext.grantPermissions`] to grant permissions for the browser context pages to read its geolocation.

# File lib/playwright_api/browser_context.rb, line 316
def set_geolocation(geolocation)
  wrap_impl(@impl.set_geolocation(unwrap_impl(geolocation)))
end
Also aliased as: geolocation=
set_offline(offline) click to toggle source
# File lib/playwright_api/browser_context.rb, line 321
def set_offline(offline)
  wrap_impl(@impl.set_offline(unwrap_impl(offline)))
end
Also aliased as: offline=
storage_state(path: nil) click to toggle source

Returns storage state for this browser context, contains current cookies and local storage snapshot.

# File lib/playwright_api/browser_context.rb, line 327
def storage_state(path: nil)
  wrap_impl(@impl.storage_state(path: unwrap_impl(path)))
end
tracing() click to toggle source
# File lib/playwright_api/browser_context.rb, line 23
def tracing # property
  wrap_impl(@impl.tracing)
end
unroute(url, handler: nil) click to toggle source

Removes a route created with [`method: BrowserContext.route`]. When `handler` is not specified, removes all routes for the `url`.

# File lib/playwright_api/browser_context.rb, line 333
def unroute(url, handler: nil)
  wrap_impl(@impl.unroute(unwrap_impl(url), handler: unwrap_impl(handler)))
end
wait_for_event(event, predicate: nil, timeout: nil) click to toggle source

> 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.

# File lib/playwright_api/browser_context.rb, line 361
def wait_for_event(event, predicate: nil, timeout: nil)
  raise NotImplementedError.new('wait_for_event is not implemented yet.')
end

Private Instance Methods

event_emitter_proxy() click to toggle source
# File lib/playwright_api/browser_context.rb, line 408
        def event_emitter_proxy
  @event_emitter_proxy ||= EventEmitterProxy.new(self, @impl)
end