Class: Playwright::BrowserContext

Inherits:
PlaywrightApi show all
Defined in:
lib/playwright_api/browser_context.rb,
sig/playwright.rbs

Overview

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 isolated non-persistent browser contexts with [method: Browser.newContext] method. Non-persistent browser contexts don't write any browsing data to disk.

# create a new incognito browser context
context = browser.new_context()
# create a new page inside context.
page = context.new_page()
page.goto("https://example.com")
# dispose context once it is no longer needed.
context.close()

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from PlaywrightApi

#initialize, unwrap, wrap

Constructor Details

This class inherits a constructor from Playwright::PlaywrightApi

Instance Attribute Details

#clockClock (readonly)

Playwright has ability to mock clock and passage of time.

Returns:



24
25
26
# File 'lib/playwright_api/browser_context.rb', line 24

def clock # property
  wrap_impl(@impl.clock)
end

#credentialsCredentials (readonly)

Virtual WebAuthn authenticator for this context. Lets tests seed credentials and intercept navigator.credentials.create() / navigator.credentials.get() ceremonies.

Returns:



31
32
33
# File 'lib/playwright_api/browser_context.rb', line 31

def credentials # property
  wrap_impl(@impl.credentials)
end

#requestAPIRequestContext (readonly)

API testing helper associated with this context. Requests made with this API will use context cookies.

Returns:



43
44
45
# File 'lib/playwright_api/browser_context.rb', line 43

def request # property
  wrap_impl(@impl.request)
end

#tracingTracing (readonly)

property

Returns:



47
48
49
# File 'lib/playwright_api/browser_context.rb', line 47

def tracing # property
  wrap_impl(@impl.tracing)
end

Instance Method Details

#add_cookies(cookies) ⇒ void

This method returns an undefined value.

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

browser_context.add_cookies([cookie_object1, cookie_object2])

Parameters:

  • cookies (Array[untyped])


60
61
62
# File 'lib/playwright_api/browser_context.rb', line 60

def add_cookies(cookies)
  wrap_impl(@impl.add_cookies(unwrap_impl(cookies)))
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:

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

Parameters:

  • path: (String, File) (defaults to: nil)
  • script: (String) (defaults to: nil)

Returns:

  • (Object)


83
84
85
# File 'lib/playwright_api/browser_context.rb', line 83

def add_init_script(path: nil, script: nil)
  wrap_impl(@impl.add_init_script(path: unwrap_impl(path), script: unwrap_impl(script)))
end

#background_pagesArray[untyped]

Deprecated.

Background pages have been removed from Chromium together with Manifest V2 extensions.

Returns an empty list.

Returns:

  • (Array[untyped])


91
92
93
# File 'lib/playwright_api/browser_context.rb', line 91

def background_pages
  wrap_impl(@impl.background_pages)
end

#browsernil, Browser

Gets the browser instance that owns the context. Returns null if the context is created outside of normal browser, e.g. Android or Electron.

Returns:



97
98
99
# File 'lib/playwright_api/browser_context.rb', line 97

def browser
  wrap_impl(@impl.browser)
end

#browser=(req) ⇒ Object



500
501
502
# File 'lib/playwright_api/browser_context.rb', line 500

def browser=(req)
  wrap_impl(@impl.browser=(unwrap_impl(req)))
end

#clear_cookies(domain: nil, name: nil, path: nil) ⇒ void

This method returns an undefined value.

Removes cookies from context. Accepts optional filter.

Usage

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

Parameters:

  • domain: (String, Regexp) (defaults to: nil)
  • name: (String, Regexp) (defaults to: nil)
  • path: (String, Regexp) (defaults to: nil)


113
114
115
# File 'lib/playwright_api/browser_context.rb', line 113

def clear_cookies(domain: nil, name: nil, path: nil)
  wrap_impl(@impl.clear_cookies(domain: unwrap_impl(domain), name: unwrap_impl(name), path: unwrap_impl(path)))
end

#clear_permissionsvoid

This method returns an undefined value.

Clears all permission overrides for the browser context.

Usage

context = browser.new_context()
context.grant_permissions(["clipboard-read"])
# do stuff ..
context.clear_permissions()


128
129
130
# File 'lib/playwright_api/browser_context.rb', line 128

def clear_permissions
  wrap_impl(@impl.clear_permissions)
end

#close(reason: nil) ⇒ void

This method returns an undefined value.

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

NOTE: The default browser context cannot be closed.

Parameters:

  • reason: (String) (defaults to: nil)


136
137
138
# File 'lib/playwright_api/browser_context.rb', line 136

def close(reason: nil)
  wrap_impl(@impl.close(reason: unwrap_impl(reason)))
end

#closed?Boolean

Indicates that the browser context is in the process of closing or has already been closed.

Returns:

  • (Boolean)


244
245
246
# File 'lib/playwright_api/browser_context.rb', line 244

def closed?
  wrap_impl(@impl.closed?)
end

#cookies(urls: nil) ⇒ Array[untyped]

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

Parameters:

  • urls: (String, Array[untyped]) (defaults to: nil)

Returns:

  • (Array[untyped])


143
144
145
# File 'lib/playwright_api/browser_context.rb', line 143

def cookies(urls: nil)
  wrap_impl(@impl.cookies(urls: unwrap_impl(urls)))
end

#debuggerObject

Debugger allows to pause and resume the execution.

Raises:

  • (NotImplementedError)


37
38
39
# File 'lib/playwright_api/browser_context.rb', line 37

def debugger # property
  raise NotImplementedError.new('debugger is not implemented yet.')
end

#enable_debug_console!Object



505
506
507
# File 'lib/playwright_api/browser_context.rb', line 505

def enable_debug_console!
  wrap_impl(@impl.enable_debug_console!)
end

#expect_console_message(predicate: nil, timeout: nil) { ... } ⇒ ConsoleMessage

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.

Parameters:

  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



462
463
464
# File 'lib/playwright_api/browser_context.rb', line 462

def expect_console_message(predicate: nil, timeout: nil, &block)
  wrap_impl(@impl.expect_console_message(predicate: unwrap_impl(predicate), timeout: unwrap_impl(timeout), &wrap_block_call(block)))
end

#expect_event(event, predicate: nil, timeout: nil) { ... } ⇒ 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

with context.expect_event("page") as event_info:
    page.get_by_role("button").click()
page = event_info.value

Parameters:

  • event (String)
  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:

  • (Object)


477
478
479
# File 'lib/playwright_api/browser_context.rb', line 477

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) { ... } ⇒ Page

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.

Parameters:

  • predicate: (function) (defaults to: nil)
  • timeout: (Float) (defaults to: nil)

Yields:

Yield Returns:

  • (void)

Returns:



485
486
487
# File 'lib/playwright_api/browser_context.rb', line 485

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

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)

Parameters:

  • name (String)
  • callback (function)

Returns:

  • (Object)


184
185
186
# File 'lib/playwright_api/browser_context.rb', line 184

def expose_binding(name, callback)
  wrap_impl(@impl.expose_binding(unwrap_impl(name), unwrap_impl(callback)))
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:

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)

Parameters:

  • name (String)
  • callback (function)

Returns:

  • (Object)


231
232
233
# File 'lib/playwright_api/browser_context.rb', line 231

def expose_function(name, callback)
  wrap_impl(@impl.expose_function(unwrap_impl(name), unwrap_impl(callback)))
end

#grant_permissions(permissions, origin: nil) ⇒ void

This method returns an undefined value.

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

Parameters:

  • permissions (Array[untyped])
  • origin: (String) (defaults to: nil)


238
239
240
# File 'lib/playwright_api/browser_context.rb', line 238

def grant_permissions(permissions, origin: nil)
  wrap_impl(@impl.grant_permissions(unwrap_impl(permissions), origin: unwrap_impl(origin)))
end

#new_cdp_session(page) ⇒ CDPSession

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

Returns the newly created session.

Parameters:

Returns:



252
253
254
# File 'lib/playwright_api/browser_context.rb', line 252

def new_cdp_session(page)
  wrap_impl(@impl.new_cdp_session(unwrap_impl(page)))
end

#new_page(&block) ⇒ void

This method returns an undefined value.

Creates a new page in the browser context.



258
259
260
# File 'lib/playwright_api/browser_context.rb', line 258

def new_page(&block)
  wrap_impl(@impl.new_page(&wrap_block_call(block)))
end

#off(event, callback) ⇒ Object

-- inherited from EventEmitter --



526
527
528
# File 'lib/playwright_api/browser_context.rb', line 526

def off(event, callback)
  event_emitter_proxy.off(event, callback)
end

#on(event, callback) ⇒ Object

-- inherited from EventEmitter --



538
539
540
# File 'lib/playwright_api/browser_context.rb', line 538

def on(event, callback)
  event_emitter_proxy.on(event, callback)
end

#once(event, callback) ⇒ Object

-- inherited from EventEmitter --



532
533
534
# File 'lib/playwright_api/browser_context.rb', line 532

def once(event, callback)
  event_emitter_proxy.once(event, callback)
end

#options=(req) ⇒ Object



520
521
522
# File 'lib/playwright_api/browser_context.rb', line 520

def options=(req)
  wrap_impl(@impl.options=(unwrap_impl(req)))
end

#owner_page=(req) ⇒ Object



515
516
517
# File 'lib/playwright_api/browser_context.rb', line 515

def owner_page=(req)
  wrap_impl(@impl.owner_page=(unwrap_impl(req)))
end

#pagesArray[untyped]

Returns all open pages in the context.

Returns:

  • (Array[untyped])


264
265
266
# File 'lib/playwright_api/browser_context.rb', line 264

def pages
  wrap_impl(@impl.pages)
end

#pauseObject



510
511
512
# File 'lib/playwright_api/browser_context.rb', line 510

def pause
  wrap_impl(@impl.pause)
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 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:

context = browser.new_context()
page = context.new_page()
context.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
page.goto("https://example.com")
browser.close()

or the same snippet using a regex pattern instead:

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("https://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:

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.

Parameters:

  • url (String, Regexp, function)
  • handler (function)
  • times: (Integer) (defaults to: nil)

Returns:

  • (Object)


315
316
317
# File 'lib/playwright_api/browser_context.rb', line 315

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) ⇒ void

This method returns an undefined value.

If specified the network requests that are made in the context will be served from the HAR file. Read more about Replaying from HAR.

Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting serviceWorkers to 'block'.

Parameters:

  • har (String, File)
  • notFound: ("abort", "fallback") (defaults to: nil)
  • update: (Boolean) (defaults to: nil)
  • updateContent: ("embed", "attach") (defaults to: nil)
  • updateMode: ("full", "minimal") (defaults to: nil)
  • url: (String, Regexp) (defaults to: nil)


323
324
325
326
327
328
329
330
331
# File 'lib/playwright_api/browser_context.rb', line 323

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

#route_web_socket(url, handler) ⇒ Object

This method allows to modify websocket connections that are made by any page in the browser context.

Note that only WebSockets created after this method was called will be routed. It is recommended to call this method before creating any pages.

Usage

Below is an example of a simple handler that blocks some websocket messages. See WebSocketRoute for more details and examples.

def message_handler(ws: WebSocketRoute, message: Union[str, bytes]):
  if message == "to-be-blocked":
    return
  ws.send(message)

def handler(ws: WebSocketRoute):
  ws.route_send(lambda message: message_handler(ws, message))
  ws.connect()

context.route_web_socket("/ws", handler)

Raises:

  • (NotImplementedError)


355
356
357
# File 'lib/playwright_api/browser_context.rb', line 355

def route_web_socket(url, handler)
  raise NotImplementedError.new('route_web_socket is not implemented yet.')
end

#service_workersArray[untyped]

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

All existing service workers in the context.

Returns:

  • (Array[untyped])


363
364
365
# File 'lib/playwright_api/browser_context.rb', line 363

def service_workers
  wrap_impl(@impl.service_workers)
end

#set_default_navigation_timeout(timeout) ⇒ void Also known as: default_navigation_timeout=

This method returns an undefined value.

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

Parameters:

  • timeout (Float)


378
379
380
# File 'lib/playwright_api/browser_context.rb', line 378

def set_default_navigation_timeout(timeout)
  wrap_impl(@impl.set_default_navigation_timeout(unwrap_impl(timeout)))
end

#set_default_timeout(timeout) ⇒ void Also known as: default_timeout=

This method returns an undefined value.

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

Parameters:

  • timeout (Float)


388
389
390
# File 'lib/playwright_api/browser_context.rb', line 388

def set_default_timeout(timeout)
  wrap_impl(@impl.set_default_timeout(unwrap_impl(timeout)))
end

#set_extra_http_headers(headers) ⇒ void Also known as: extra_http_headers=

This method returns an undefined value.

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.

Parameters:

  • headers (Hash[untyped, untyped])


399
400
401
# File 'lib/playwright_api/browser_context.rb', line 399

def set_extra_http_headers(headers)
  wrap_impl(@impl.set_extra_http_headers(unwrap_impl(headers)))
end

#set_geolocation(geolocation) ⇒ void Also known as: geolocation=

This method returns an undefined value.

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

Usage

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.

Parameters:

  • geolocation (nil, Hash[untyped, untyped])


415
416
417
# File 'lib/playwright_api/browser_context.rb', line 415

def set_geolocation(geolocation)
  wrap_impl(@impl.set_geolocation(unwrap_impl(geolocation)))
end

#set_offline(offline) ⇒ void Also known as: offline=

This method returns an undefined value.

Parameters:

  • offline (Boolean)


420
421
422
# File 'lib/playwright_api/browser_context.rb', line 420

def set_offline(offline)
  wrap_impl(@impl.set_offline(unwrap_impl(offline)))
end

#set_storage_state(storageState) ⇒ void Also known as: storage_state=

This method returns an undefined value.

Clears the existing cookies, local storage and IndexedDB entries for all origins and sets the new storage state.

Usage

# Load storage state from a file and apply it to the context.
context.set_storage_state("state.json")

Parameters:

  • storageState ((String | File), Hash[untyped, untyped])


440
441
442
# File 'lib/playwright_api/browser_context.rb', line 440

def set_storage_state(storageState)
  wrap_impl(@impl.set_storage_state(unwrap_impl(storageState)))
end

#storage_state(indexedDB: nil, path: nil) ⇒ Hash[untyped, untyped]

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

Parameters:

  • indexedDB: (Boolean) (defaults to: nil)
  • path: (String, File) (defaults to: nil)

Returns:

  • (Hash[untyped, untyped])


427
428
429
# File 'lib/playwright_api/browser_context.rb', line 427

def storage_state(indexedDB: nil, path: nil)
  wrap_impl(@impl.storage_state(indexedDB: unwrap_impl(indexedDB), path: unwrap_impl(path)))
end

#unroute(url, handler: nil) ⇒ void

This method returns an undefined value.

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

Parameters:

  • url (String, Regexp, function)
  • handler: (function) (defaults to: nil)


454
455
456
# File 'lib/playwright_api/browser_context.rb', line 454

def unroute(url, handler: nil)
  wrap_impl(@impl.unroute(unwrap_impl(url), handler: unwrap_impl(handler)))
end

#unroute_all(behavior: nil) ⇒ void

This method returns an undefined value.

Removes all routes created with [method: BrowserContext.route] and [method: BrowserContext.routeFromHAR].

Parameters:

  • behavior: ("wait", "ignoreErrors", "default") (defaults to: nil)


447
448
449
# File 'lib/playwright_api/browser_context.rb', line 447

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.

Raises:

  • (NotImplementedError)


495
496
497
# File 'lib/playwright_api/browser_context.rb', line 495

def wait_for_event(event, predicate: nil, timeout: nil)
  raise NotImplementedError.new('wait_for_event is not implemented yet.')
end