Qucs-S S-parameter Viewer & RF Synthesis Tools
Loading...
Searching...
No Matches
Public Member Functions | List of all members
playwright.sync_api._generated.BrowserContext Class Reference
Inheritance diagram for playwright.sync_api._generated.BrowserContext:
Inheritance graph
[legend]
Collaboration diagram for playwright.sync_api._generated.BrowserContext:
Collaboration graph
[legend]

Public Member Functions

None on (self, Literal["backgroundpage"] event, typing.Callable[["Page"], "None"] f)
 
None on (self, Literal["close"] event, typing.Callable[["BrowserContext"], "None"] f)
 
None on (self, Literal["console"] event, typing.Callable[["ConsoleMessage"], "None"] f)
 
None on (self, Literal["dialog"] event, typing.Callable[["Dialog"], "None"] f)
 
None on (self, Literal["page"] event, typing.Callable[["Page"], "None"] f)
 
None on (self, Literal["weberror"] event, typing.Callable[["WebError"], "None"] f)
 
None on (self, Literal["request"] event, typing.Callable[["Request"], "None"] f)
 
None on (self, Literal["requestfailed"] event, typing.Callable[["Request"], "None"] f)
 
None on (self, Literal["requestfinished"] event, typing.Callable[["Request"], "None"] f)
 
None on (self, Literal["response"] event, typing.Callable[["Response"], "None"] f)
 
None on (self, Literal["serviceworker"] event, typing.Callable[["Worker"], "None"] f)
 
None on (self, str event, typing.Callable[..., None] f)
 
None once (self, Literal["backgroundpage"] event, typing.Callable[["Page"], "None"] f)
 
None once (self, Literal["close"] event, typing.Callable[["BrowserContext"], "None"] f)
 
None once (self, Literal["console"] event, typing.Callable[["ConsoleMessage"], "None"] f)
 
None once (self, Literal["dialog"] event, typing.Callable[["Dialog"], "None"] f)
 
None once (self, Literal["page"] event, typing.Callable[["Page"], "None"] f)
 
None once (self, Literal["weberror"] event, typing.Callable[["WebError"], "None"] f)
 
None once (self, Literal["request"] event, typing.Callable[["Request"], "None"] f)
 
None once (self, Literal["requestfailed"] event, typing.Callable[["Request"], "None"] f)
 
None once (self, Literal["requestfinished"] event, typing.Callable[["Request"], "None"] f)
 
None once (self, Literal["response"] event, typing.Callable[["Response"], "None"] f)
 
None once (self, Literal["serviceworker"] event, typing.Callable[["Worker"], "None"] f)
 
None once (self, str event, typing.Callable[..., None] f)
 
typing.List["Page"] pages (self)
 
typing.Optional["Browser"] browser (self)
 
typing.List["Page"] background_pages (self)
 
typing.List["Worker"] service_workers (self)
 
"Tracing" tracing (self)
 
"APIRequestContext" request (self)
 
"Clock" clock (self)
 
None set_default_navigation_timeout (self, float timeout)
 
None set_default_timeout (self, float timeout)
 
"Page" new_page (self)
 
typing.List[Cookiecookies (self, typing.Optional[typing.Union[str, typing.Sequence[str]]] urls=None)
 
None add_cookies (self, typing.Sequence[SetCookieParam] cookies)
 
None clear_cookies (self, *typing.Optional[typing.Union[typing.Pattern[str], str]] name=None, typing.Optional[typing.Union[typing.Pattern[str], str]] domain=None, typing.Optional[typing.Union[typing.Pattern[str], str]] path=None)
 
None grant_permissions (self, typing.Sequence[str] permissions, *typing.Optional[str] origin=None)
 
None clear_permissions (self)
 
None set_geolocation (self, typing.Optional[Geolocation] geolocation=None)
 
None set_extra_http_headers (self, typing.Dict[str, str] headers)
 
None set_offline (self, bool offline)
 
None add_init_script (self, typing.Optional[str] script=None, *typing.Optional[typing.Union[pathlib.Path, str]] path=None)
 
None expose_binding (self, str name, typing.Callable callback, *typing.Optional[bool] handle=None)
 
None expose_function (self, str name, typing.Callable callback)
 
None route (self, typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]] url, typing.Union[typing.Callable[["Route"], typing.Any], typing.Callable[["Route", "Request"], typing.Any],] handler, *typing.Optional[int] times=None)
 
None unroute (self, typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]] url, typing.Optional[typing.Union[typing.Callable[["Route"], typing.Any], typing.Callable[["Route", "Request"], typing.Any],]] handler=None)
 
None route_web_socket (self, typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]] url, typing.Callable[["WebSocketRoute"], typing.Any] handler)
 
None unroute_all (self, *typing.Optional[Literal["default", "ignoreErrors", "wait"]] behavior=None)
 
None route_from_har (self, typing.Union[pathlib.Path, str] har, *typing.Optional[typing.Union[typing.Pattern[str], str]] url=None, typing.Optional[Literal["abort", "fallback"]] not_found=None, typing.Optional[bool] update=None, typing.Optional[Literal["attach", "embed"]] update_content=None, typing.Optional[Literal["full", "minimal"]] update_mode=None)
 
EventContextManager expect_event (self, str event, typing.Optional[typing.Callable] predicate=None, *typing.Optional[float] timeout=None)
 
None close (self, *typing.Optional[str] reason=None)
 
StorageState storage_state (self, *typing.Optional[typing.Union[pathlib.Path, str]] path=None, typing.Optional[bool] indexed_db=None)
 
typing.Any wait_for_event (self, str event, typing.Optional[typing.Callable] predicate=None, *typing.Optional[float] timeout=None)
 
EventContextManager["ConsoleMessage"] expect_console_message (self, typing.Optional[typing.Callable[["ConsoleMessage"], bool]] predicate=None, *typing.Optional[float] timeout=None)
 
EventContextManager["Page"] expect_page (self, typing.Optional[typing.Callable[["Page"], bool]] predicate=None, *typing.Optional[float] timeout=None)
 
"CDPSession" new_cdp_session (self, typing.Union["Page", "Frame"] page)
 
- Public Member Functions inherited from playwright._impl._sync_base.SyncContextManager
Self __enter__ (Self self)
 
None __exit__ (self, Optional[Type[BaseException]] exc_type, Optional[BaseException] exc_val, Optional[TracebackType] _traceback)
 
- Public Member Functions inherited from playwright._impl._sync_base.SyncBase
None __init__ (self, Any impl_obj)
 
str __str__ (self)
 
None remove_listener (self, Any event, Any f)
 
- Public Member Functions inherited from playwright._impl._impl_to_api_mapping.ImplWrapper
str __repr__ (self)
 

Additional Inherited Members

- Protected Member Functions inherited from playwright._impl._sync_base.SyncBase
Any _sync (self, Union[Coroutine[Any, Any, Any], Generator[Any, Any, Any]] coro)
 
Callable[..., None] _wrap_handler (self, Union[Callable[..., Any], Any] handler)
 
- Protected Attributes inherited from playwright._impl._sync_base.SyncBase
 _dispatcher_fiber
 
 _loop
 
- Protected Attributes inherited from playwright._impl._impl_to_api_mapping.ImplWrapper
 _impl_obj
 

Member Function Documentation

◆ add_cookies()

None playwright.sync_api._generated.BrowserContext.add_cookies (   self,
typing.Sequence[SetCookieParam cookies 
)
BrowserContext.add_cookies

Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies
can be obtained via `browser_context.cookies()`.

**Usage**

```py
browser_context.add_cookies([cookie_object1, cookie_object2])
```

Parameters
----------
cookies : Sequence[{name: str, value: str, url: Union[str, None], domain: Union[str, None], path: Union[str, None], expires: Union[float, None], httpOnly: Union[bool, None], secure: Union[bool, None], sameSite: Union["Lax", "None", "Strict", None], partitionKey: Union[str, None]}]

◆ add_init_script()

None playwright.sync_api._generated.BrowserContext.add_init_script (   self,
typing.Optional[str]   script = None,
*typing.Optional[typing.Union[pathlib.Path, str]]   path = None 
)
BrowserContext.add_init_script

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:

```py
# 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 `browser_context.add_init_script()` and
`page.add_init_script()` is not defined.

Parameters
----------
script : Union[str, None]
    Script to be evaluated in all pages in the browser context. Optional.
path : Union[pathlib.Path, str, None]
    Path to the JavaScript file. If `path` is a relative path, then it is resolved relative to the current working
    directory. Optional.

◆ background_pages()

typing.List["Page"] playwright.sync_api._generated.BrowserContext.background_pages (   self)
BrowserContext.background_pages

Returns an empty list.

Returns
-------
List[Page]

◆ browser()

typing.Optional["Browser"] playwright.sync_api._generated.BrowserContext.browser (   self)
BrowserContext.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
-------
Union[Browser, None]

◆ clear_cookies()

None playwright.sync_api._generated.BrowserContext.clear_cookies (   self,
*typing.Optional[typing.Union[typing.Pattern[str], str]]   name = None,
typing.Optional[typing.Union[typing.Pattern[str], str]]   domain = None,
typing.Optional[typing.Union[typing.Pattern[str], str]]   path = None 
)
BrowserContext.clear_cookies

Removes cookies from context. Accepts optional filter.

**Usage**

```py
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
----------
name : Union[Pattern[str], str, None]
    Only removes cookies with the given name.
domain : Union[Pattern[str], str, None]
    Only removes cookies with the given domain.
path : Union[Pattern[str], str, None]
    Only removes cookies with the given path.

◆ clear_permissions()

None playwright.sync_api._generated.BrowserContext.clear_permissions (   self)
BrowserContext.clear_permissions

Clears all permission overrides for the browser context.

**Usage**

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

◆ clock()

"Clock" playwright.sync_api._generated.BrowserContext.clock (   self)
BrowserContext.clock

Playwright has ability to mock clock and passage of time.

Returns
-------
Clock

◆ close()

None playwright.sync_api._generated.BrowserContext.close (   self,
*typing.Optional[str]   reason = None 
)
BrowserContext.close

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 : Union[str, None]
    The reason to be reported to the operations interrupted by the context closure.

Reimplemented from playwright._impl._sync_base.SyncContextManager.

◆ cookies()

typing.List[Cookie] playwright.sync_api._generated.BrowserContext.cookies (   self,
typing.Optional[typing.Union[str, typing.Sequence[str]]]   urls = None 
)
BrowserContext.cookies

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

Parameters
----------
urls : Union[Sequence[str], str, None]
    Optional list of URLs.

Returns
-------
List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"], partitionKey: Union[str, None]}]

◆ expect_console_message()

EventContextManager["ConsoleMessage"] playwright.sync_api._generated.BrowserContext.expect_console_message (   self,
typing.Optional[typing.Callable[["ConsoleMessage"], bool]]   predicate = None,
*typing.Optional[float]   timeout = None 
)
BrowserContext.expect_console_message

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 `browser_context.on('console')` event
is fired.

Parameters
----------
predicate : Union[Callable[[ConsoleMessage], bool], None]
    Receives the `ConsoleMessage` object and resolves to truthy value when the waiting should resolve.
timeout : Union[float, None]
    Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
    default value can be changed by using the `browser_context.set_default_timeout()`.

Returns
-------
EventContextManager[ConsoleMessage]

◆ expect_event()

EventContextManager playwright.sync_api._generated.BrowserContext.expect_event (   self,
str  event,
typing.Optional[typing.Callable]   predicate = None,
*typing.Optional[float]   timeout = None 
)
BrowserContext.expect_event

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

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

Parameters
----------
event : str
    Event name, same one would pass into `browserContext.on(event)`.
predicate : Union[Callable, None]
    Receives the event data and resolves to truthy value when the waiting should resolve.
timeout : Union[float, None]
    Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
    default value can be changed by using the `browser_context.set_default_timeout()`.

Returns
-------
EventContextManager

◆ expect_page()

EventContextManager["Page"] playwright.sync_api._generated.BrowserContext.expect_page (   self,
typing.Optional[typing.Callable[["Page"], bool]]   predicate = None,
*typing.Optional[float]   timeout = None 
)
BrowserContext.expect_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 : Union[Callable[[Page], bool], None]
    Receives the `Page` object and resolves to truthy value when the waiting should resolve.
timeout : Union[float, None]
    Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
    default value can be changed by using the `browser_context.set_default_timeout()`.

Returns
-------
EventContextManager[Page]

◆ expose_binding()

None playwright.sync_api._generated.BrowserContext.expose_binding (   self,
str  name,
typing.Callable  callback,
*typing.Optional[bool]   handle = None 
)
BrowserContext.expose_binding

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 `page.expose_binding()` for page-only version.

**Usage**

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

```py
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 : str
    Name of the function on the window object.
callback : Callable
    Callback function that will be called in the Playwright's context.
handle : Union[bool, None]
    Whether to pass the argument as a handle, instead of passing by value. When passing a handle, only one argument is
    supported. When passing by value, multiple arguments are supported.
    Deprecated: This option will be removed in the future.

◆ expose_function()

None playwright.sync_api._generated.BrowserContext.expose_function (   self,
str  name,
typing.Callable  callback 
)
BrowserContext.expose_function

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 `page.expose_function()` for page-only version.

**Usage**

An example of adding a `sha256` function to all pages in the context:

```py
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 : str
    Name of the function on the window object.
callback : Callable
    Callback function that will be called in the Playwright's context.

◆ grant_permissions()

None playwright.sync_api._generated.BrowserContext.grant_permissions (   self,
typing.Sequence[str]  permissions,
*typing.Optional[str]   origin = None 
)
BrowserContext.grant_permissions

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

Parameters
----------
permissions : Sequence[str]
    A list of permissions to grant.

    **NOTE** Supported permissions differ between browsers, and even between different versions of the same browser.
    Any permission may stop working after an update.

    Here are some permissions that may be supported by some browsers:
    - `'accelerometer'`
    - `'ambient-light-sensor'`
    - `'background-sync'`
    - `'camera'`
    - `'clipboard-read'`
    - `'clipboard-write'`
    - `'geolocation'`
    - `'gyroscope'`
    - `'local-fonts'`
    - `'local-network-access'`
    - `'magnetometer'`
    - `'microphone'`
    - `'midi-sysex'` (system-exclusive midi)
    - `'midi'`
    - `'notifications'`
    - `'payment-handler'`
    - `'storage-access'`
origin : Union[str, None]
    The [origin] to grant permissions to, e.g. "https://example.com".

◆ new_cdp_session()

"CDPSession" playwright.sync_api._generated.BrowserContext.new_cdp_session (   self,
typing.Union["Page", "Frame"]  page 
)
BrowserContext.new_cdp_session

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

Returns the newly created session.

Parameters
----------
page : Union[Frame, Page]
    Target to create new session for. For backwards-compatibility, this parameter is named `page`, but it can be a
    `Page` or `Frame` type.

Returns
-------
CDPSession

◆ new_page()

"Page" playwright.sync_api._generated.BrowserContext.new_page (   self)
BrowserContext.new_page

Creates a new page in the browser context.

Returns
-------
Page

◆ on() [1/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["backgroundpage"]  event,
typing.Callable[["Page"], "None"]   f 
)
This event is not emitted.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [2/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["close"]  event,
typing.Callable[["BrowserContext"], "None"]   f 
)
Emitted when Browser context gets closed. This might happen because of one of the following:
- Browser context is closed.
- Browser application is closed or crashed.
- The `browser.close()` method was called.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [3/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["console"]  event,
typing.Callable[["ConsoleMessage"], "None"]   f 
)
Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.

The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.

**Usage**

```py
def print_args(msg):
    for arg in msg.args:
        print(arg.json_value())

context.on(\"console\", print_args)
page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
```

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [4/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["dialog"]  event,
typing.Callable[["Dialog"], "None"]   f 
)
Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
[freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
and actions like click will never finish.

**Usage**

```python
context.on(\"dialog\", lambda dialog: dialog.accept())
```

**NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
automatically dismissed.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [5/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["page"]  event,
typing.Callable[["Page"], "None"]  f 
)
The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
specific page.

The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
popup with `window.open('http://example.com')`, this event will fire when the network request to
\"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
instead of similar methods on the `Page`.

```py
with context.expect_page() as page_info:
    page.get_by_text(\"open new page\").click(),
page = page_info.value
print(page.evaluate(\"location.href\"))
```

**NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
need it in most cases).

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [6/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["request"]  event,
typing.Callable[["Request"], "None"]   f 
)
Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
only listen for requests from a particular page, use `page.on('request')`.

In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [7/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["requestfailed"]  event,
typing.Callable[["Request"], "None"]   f 
)
Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
use `page.on('request_failed')`.

**NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
will complete with `browser_context.on('request_finished')` event and not with
`browser_context.on('request_failed')`.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [8/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["requestfinished"]  event,
typing.Callable[["Request"], "None"]   f 
)
Emitted when a request finishes successfully after downloading the response body. For a successful response, the
sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
particular page, use `page.on('request_finished')`.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [9/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["response"]  event,
typing.Callable[["Response"], "None"]   f 
)
Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
`page.on('response')`.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [10/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["serviceworker"]  event,
typing.Callable[["Worker"], "None"]   f 
)
**NOTE** Service workers are only supported on Chromium-based browsers.

Emitted when new service worker is created in the context.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [11/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
Literal["weberror"]  event,
typing.Callable[["WebError"], "None"]   f 
)
Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
page, use `page.on('page_error')` instead.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ on() [12/12]

None playwright.sync_api._generated.BrowserContext.on (   self,
str  event,
typing.Callable[..., None]  f 
)
Registers the function ``f`` to the event name ``event``.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [1/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["backgroundpage"]  event,
typing.Callable[["Page"], "None"]   f 
)
This event is not emitted.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [2/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["close"]  event,
typing.Callable[["BrowserContext"], "None"]   f 
)
Emitted when Browser context gets closed. This might happen because of one of the following:
- Browser context is closed.
- Browser application is closed or crashed.
- The `browser.close()` method was called.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [3/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["console"]  event,
typing.Callable[["ConsoleMessage"], "None"]   f 
)
Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`.

The arguments passed into `console.log` and the page are available on the `ConsoleMessage` event handler argument.

**Usage**

```py
def print_args(msg):
    for arg in msg.args:
        print(arg.json_value())

context.on(\"console\", print_args)
page.evaluate(\"console.log('hello', 5, { foo: 'bar' })\")
```

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [4/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["dialog"]  event,
typing.Callable[["Dialog"], "None"]   f 
)
Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Listener **must**
either `dialog.accept()` or `dialog.dismiss()` the dialog - otherwise the page will
[freeze](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#never_blocking) waiting for the dialog,
and actions like click will never finish.

**Usage**

```python
context.on(\"dialog\", lambda dialog: dialog.accept())
```

**NOTE** When no `page.on('dialog')` or `browser_context.on('dialog')` listeners are present, all dialogs are
automatically dismissed.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [5/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["page"]  event,
typing.Callable[["Page"], "None"]   f 
)
The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event
will also fire for popup pages. See also `page.on('popup')` to receive events about popups relevant to a
specific page.

The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a
popup with `window.open('http://example.com')`, this event will fire when the network request to
\"http://example.com\" is done and its response has started loading in the popup. If you would like to route/listen
to this network request, use `browser_context.route()` and `browser_context.on('request')` respectively
instead of similar methods on the `Page`.

```py
with context.expect_page() as page_info:
    page.get_by_text(\"open new page\").click(),
page = page_info.value
print(page.evaluate(\"location.href\"))
```

**NOTE** Use `page.wait_for_load_state()` to wait until the page gets to a particular state (you should not
need it in most cases).

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [6/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["request"]  event,
typing.Callable[["Request"], "None"]   f 
)
Emitted when a request is issued from any pages created through this context. The [request] object is read-only. To
only listen for requests from a particular page, use `page.on('request')`.

In order to intercept and mutate requests, see `browser_context.route()` or `page.route()`.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [7/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["requestfailed"]  event,
typing.Callable[["Request"], "None"]   f 
)
Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page,
use `page.on('request_failed')`.

**NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request
will complete with `browser_context.on('request_finished')` event and not with
`browser_context.on('request_failed')`.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [8/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["requestfinished"]  event,
typing.Callable[["Request"], "None"]   f 
)
Emitted when a request finishes successfully after downloading the response body. For a successful response, the
sequence of events is `request`, `response` and `requestfinished`. To listen for successful requests from a
particular page, use `page.on('request_finished')`.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [9/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["response"]  event,
typing.Callable[["Response"], "None"]   f 
)
Emitted when [response] status and headers are received for a request. For a successful response, the sequence of
events is `request`, `response` and `requestfinished`. To listen for response events from a particular page, use
`page.on('response')`.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [10/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["serviceworker"]  event,
typing.Callable[["Worker"], "None"]   f 
)
**NOTE** Service workers are only supported on Chromium-based browsers.

Emitted when new service worker is created in the context.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [11/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
Literal["weberror"]  event,
typing.Callable[["WebError"], "None"]   f 
)
Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular
page, use `page.on('page_error')` instead.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ once() [12/12]

None playwright.sync_api._generated.BrowserContext.once (   self,
str  event,
typing.Callable[..., None]  f 
)
The same as ``self.on``, except that the listener is automatically
removed after being called.

Reimplemented from playwright._impl._sync_base.SyncBase.

◆ pages()

typing.List["Page"] playwright.sync_api._generated.BrowserContext.pages (   self)
BrowserContext.pages

Returns all open pages in the context.

Returns
-------
List[Page]

◆ request()

"APIRequestContext" playwright.sync_api._generated.BrowserContext.request (   self)
BrowserContext.request

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

Returns
-------
APIRequestContext

◆ route()

None playwright.sync_api._generated.BrowserContext.route (   self,
typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]  url,
typing.Union[ typing.Callable[["Route"], typing.Any], typing.Callable[["Route", "Request"], typing.Any], ]  handler,
*typing.Optional[int]   times = None 
)
BrowserContext.route

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** `browser_context.route()` will not intercept requests intercepted by Service Worker. See
[this](https://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:

```py
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:

```py
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:

```py
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 `page.route()`) take precedence over browser context routes when request matches
both handlers.

To remove a route with its handler you can use `browser_context.unroute()`.

**NOTE** Enabling routing disables http cache.

Parameters
----------
url : Union[Callable[[str], bool], Pattern[str], str]
    A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If `baseURL` is set in
    the context options and the provided URL is a string that does not start with `*`, it is resolved using the
    [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) constructor.
handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any]]
    handler function to route the request.
times : Union[int, None]
    How often a route should be used. By default it will be used every time.

◆ route_from_har()

None playwright.sync_api._generated.BrowserContext.route_from_har (   self,
typing.Union[pathlib.Path, str]  har,
*typing.Optional[typing.Union[typing.Pattern[str], str]]   url = None,
typing.Optional[Literal["abort", "fallback"]]   not_found = None,
typing.Optional[bool]   update = None,
typing.Optional[Literal["attach", "embed"]]   update_content = None,
typing.Optional[Literal["full", "minimal"]]   update_mode = None 
)
BrowserContext.route_from_har

If specified the network requests that are made in the context will be served from the HAR file. Read more about
[Replaying from HAR](https://playwright.dev/python/docs/mock#replaying-from-har).

Playwright will not serve requests intercepted by Service Worker from the HAR file. See
[this](https://github.com/microsoft/playwright/issues/1090) issue. We recommend disabling Service Workers when
using request interception by setting `serviceWorkers` to `'block'`.

Parameters
----------
har : Union[pathlib.Path, str]
    Path to a [HAR](http://www.softwareishard.com/blog/har-12-spec) file with prerecorded network data. If `path` is a
    relative path, then it is resolved relative to the current working directory.
url : Union[Pattern[str], str, None]
    A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the
    pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
not_found : Union["abort", "fallback", None]
    - If set to 'abort' any request not found in the HAR file will be aborted.
    - If set to 'fallback' falls through to the next route handler in the handler chain.

    Defaults to abort.
update : Union[bool, None]
    If specified, updates the given HAR with the actual network information instead of serving from file. The file is
    written to disk when `browser_context.close()` is called.
update_content : Union["attach", "embed", None]
    Optional setting to control resource content management. If `attach` is specified, resources are persisted as
    separate files or entries in the ZIP archive. If `embed` is specified, content is stored inline the HAR file.
update_mode : Union["full", "minimal", None]
    When set to `minimal`, only record information necessary for routing from HAR. This omits sizes, timing, page,
    cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to
    `minimal`.

◆ route_web_socket()

None playwright.sync_api._generated.BrowserContext.route_web_socket (   self,
typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]  url,
typing.Callable[["WebSocketRoute"], typing.Any]  handler 
)
BrowserContext.route_web_socket

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

Note that only `WebSocket`s 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.

```py
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)
```

Parameters
----------
url : Union[Callable[[str], bool], Pattern[str], str]
    Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the
    `baseURL` context option.
handler : Callable[[WebSocketRoute], Any]
    Handler function to route the WebSocket.

◆ service_workers()

typing.List["Worker"] playwright.sync_api._generated.BrowserContext.service_workers (   self)
BrowserContext.service_workers

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

All existing service workers in the context.

Returns
-------
List[Worker]

◆ set_default_navigation_timeout()

None playwright.sync_api._generated.BrowserContext.set_default_navigation_timeout (   self,
float  timeout 
)
BrowserContext.set_default_navigation_timeout

This setting will change the default maximum navigation time for the following methods and related shortcuts:
- `page.go_back()`
- `page.go_forward()`
- `page.goto()`
- `page.reload()`
- `page.set_content()`
- `page.expect_navigation()`

**NOTE** `page.set_default_navigation_timeout()` and `page.set_default_timeout()` take priority over
`browser_context.set_default_navigation_timeout()`.

Parameters
----------
timeout : float
    Maximum navigation time in milliseconds

◆ set_default_timeout()

None playwright.sync_api._generated.BrowserContext.set_default_timeout (   self,
float  timeout 
)
BrowserContext.set_default_timeout

This setting will change the default maximum time for all the methods accepting `timeout` option.

**NOTE** `page.set_default_navigation_timeout()`, `page.set_default_timeout()` and
`browser_context.set_default_navigation_timeout()` take priority over
`browser_context.set_default_timeout()`.

Parameters
----------
timeout : float
    Maximum time in milliseconds. Pass `0` to disable timeout.

◆ set_extra_http_headers()

None playwright.sync_api._generated.BrowserContext.set_extra_http_headers (   self,
typing.Dict[str, str]  headers 
)
BrowserContext.set_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 `page.set_extra_http_headers()`. If page overrides a
particular header, page-specific header value will be used instead of the browser context header value.

**NOTE** `browser_context.set_extra_http_headers()` does not guarantee the order of headers in the outgoing
requests.

Parameters
----------
headers : Dict[str, str]
    An object containing additional HTTP headers to be sent with every request. All header values must be strings.

◆ set_geolocation()

None playwright.sync_api._generated.BrowserContext.set_geolocation (   self,
typing.Optional[Geolocation]   geolocation = None 
)
BrowserContext.set_geolocation

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

**Usage**

```py
browser_context.set_geolocation({\"latitude\": 59.95, \"longitude\": 30.31667})
```

**NOTE** Consider using `browser_context.grant_permissions()` to grant permissions for the browser context
pages to read its geolocation.

Parameters
----------
geolocation : Union[{latitude: float, longitude: float, accuracy: Union[float, None]}, None]

◆ set_offline()

None playwright.sync_api._generated.BrowserContext.set_offline (   self,
bool  offline 
)
BrowserContext.set_offline

Parameters
----------
offline : bool
    Whether to emulate network being offline for the browser context.

◆ storage_state()

StorageState playwright.sync_api._generated.BrowserContext.storage_state (   self,
*typing.Optional[typing.Union[pathlib.Path, str]]   path = None,
typing.Optional[bool]   indexed_db = None 
)
BrowserContext.storage_state

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

Parameters
----------
path : Union[pathlib.Path, str, None]
    The file path to save the storage state to. If `path` is a relative path, then it is resolved relative to current
    working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
indexed_db : Union[bool, None]
    Set to `true` to include [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) in the storage
    state snapshot. If your application uses IndexedDB to store authentication tokens, like Firebase Authentication,
    enable this.

Returns
-------
{cookies: List[{name: str, value: str, domain: str, path: str, expires: float, httpOnly: bool, secure: bool, sameSite: Union["Lax", "None", "Strict"]}], origins: List[{origin: str, localStorage: List[{name: str, value: str}]}]}

◆ tracing()

"Tracing" playwright.sync_api._generated.BrowserContext.tracing (   self)
BrowserContext.tracing

Returns
-------
Tracing

◆ unroute()

None playwright.sync_api._generated.BrowserContext.unroute (   self,
typing.Union[str, typing.Pattern[str], typing.Callable[[str], bool]]  url,
typing.Optional[ typing.Union[ typing.Callable[["Route"], typing.Any], typing.Callable[["Route", "Request"], typing.Any], ] ]   handler = None 
)
BrowserContext.unroute

Removes a route created with `browser_context.route()`. When `handler` is not specified, removes all routes
for the `url`.

Parameters
----------
url : Union[Callable[[str], bool], Pattern[str], str]
    A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with
    `browser_context.route()`.
handler : Union[Callable[[Route, Request], Any], Callable[[Route], Any], None]
    Optional handler function used to register a routing with `browser_context.route()`.

◆ unroute_all()

None playwright.sync_api._generated.BrowserContext.unroute_all (   self,
*typing.Optional[Literal["default", "ignoreErrors", "wait"]]   behavior = None 
)
BrowserContext.unroute_all

Removes all routes created with `browser_context.route()` and `browser_context.route_from_har()`.

Parameters
----------
behavior : Union["default", "ignoreErrors", "wait", None]
    Specifies whether to wait for already running handlers and what to do if they throw errors:
    - `'default'` - do not wait for current handler calls (if any) to finish, if unrouted handler throws, it may
      result in unhandled error
    - `'wait'` - wait for current handler calls (if any) to finish
    - `'ignoreErrors'` - do not wait for current handler calls (if any) to finish, all errors thrown by the handlers
      after unrouting are silently caught

◆ wait_for_event()

typing.Any playwright.sync_api._generated.BrowserContext.wait_for_event (   self,
str  event,
typing.Optional[typing.Callable]   predicate = None,
*typing.Optional[float]   timeout = None 
)
BrowserContext.wait_for_event

**NOTE** In most cases, you should use `browser_context.expect_event()`.

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.

Parameters
----------
event : str
    Event name, same one typically passed into `*.on(event)`.
predicate : Union[Callable, None]
    Receives the event data and resolves to truthy value when the waiting should resolve.
timeout : Union[float, None]
    Maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The
    default value can be changed by using the `browser_context.set_default_timeout()`.

Returns
-------
Any

The documentation for this class was generated from the following file: