BrowserContext
- 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 browser.new_context(**kwargs) method. "Incognito" browser contexts don't write any browsing data to disk.
- Sync
- Async
# 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()
# create a new incognito browser context
context = await browser.new_context()
# create a new page inside context.
page = await context.new_page()
await page.goto("https://example.com")
# dispose context once it is no longer needed.
await context.close()
- browser_context.on("backgroundpage")
- browser_context.on("close")
- browser_context.on("page")
- browser_context.on("request")
- browser_context.on("requestfailed")
- browser_context.on("requestfinished")
- browser_context.on("response")
- browser_context.on("serviceworker")
- browser_context.add_cookies(cookies)
- browser_context.add_init_script(**kwargs)
- browser_context.background_pages
- browser_context.browser
- browser_context.clear_cookies()
- browser_context.clear_permissions()
- browser_context.close()
- browser_context.cookies(**kwargs)
- browser_context.expect_event(event, **kwargs)
- browser_context.expect_page(**kwargs)
- browser_context.expose_binding(name, callback, **kwargs)
- browser_context.expose_function(name, callback)
- browser_context.grant_permissions(permissions, **kwargs)
- browser_context.new_cdp_session(page)
- browser_context.new_page()
- browser_context.pages
- browser_context.request
- browser_context.route(url, handler, **kwargs)
- browser_context.route_from_har(har, **kwargs)
- browser_context.service_workers
- browser_context.set_default_navigation_timeout(timeout)
- browser_context.set_default_timeout(timeout)
- browser_context.set_extra_http_headers(headers)
- browser_context.set_geolocation(geolocation)
- browser_context.set_offline(offline)
- browser_context.storage_state(**kwargs)
- browser_context.tracing
- browser_context.unroute(url, **kwargs)
- browser_context.wait_for_event(event, **kwargs)
browser_context.on("backgroundpage")
Added in: v1.11- type: <Page>
Only works with Chromium browser's persistent context.
Emitted when new background page is created in the context.
- Sync
- Async
background_page = context.wait_for_event("backgroundpage")
background_page = await context.wait_for_event("backgroundpage")
browser_context.on("close")
Added in: v1.8- type: <BrowserContext>
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.
browser_context.on("page")
Added in: v1.8- type: <Page>
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.
- Sync
- Async
with context.expect_page() as page_info:
page.locator("a[target=_blank]").click(),
page = page_info.value
print(page.evaluate("location.href"))
async with context.expect_page() as page_info:
await page.locator("a[target=_blank]").click(),
page = await page_info.value
print(await page.evaluate("location.href"))
Use page.wait_for_load_state(**kwargs) to wait until the page gets to a particular state (you should not need it in most cases).
browser_context.on("request")
Added in: v1.12- type: <Request>
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(url, handler, **kwargs) or page.route(url, handler, **kwargs).
browser_context.on("requestfailed")
Added in: v1.12- type: <Request>
Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use page.on("requestfailed").
HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with browser_context.on("requestfinished") event and not with browser_context.on("requestfailed").
browser_context.on("requestfinished")
Added in: v1.12- type: <Request>
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("requestfinished").
browser_context.on("response")
Added in: v1.12- type: <Response>
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").
browser_context.on("serviceworker")
Added in: v1.11- type: <Worker>
Service workers are only supported on Chromium-based browsers.
Emitted when new service worker is created in the context.
browser_context.add_cookies(cookies)
Added in: v1.8cookies
<List[Dict]>#name
<str>value
<str>url
<str> either url or domain / path are required. Optional.domain
<str> either url or domain / path are required Optional.path
<str> either url or domain / path are required Optional.expires
<float> Unix time in seconds. Optional.httpOnly
<bool> Optional.secure
<bool> Optional.sameSite
<"Strict"|"Lax"|"None"> Optional.
- returns:NoneType># <
Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via browser_context.cookies(**kwargs).
- Sync
- Async
browser_context.add_cookies([cookie_object1, cookie_object2])
await browser_context.add_cookies([cookie_object1, cookie_object2])
browser_context.add_init_script(**kwargs)
Added in: v1.8path
<Union[str, pathlib.Path]> Path to the JavaScript file. Ifpath
is a relative path, then it is resolved relative to the current working directory. Optional.#script
<str> Script to be evaluated in all pages in the browser context. Optional.#- returns:NoneType># <
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:
// preload.js
Math.random = () => 42;
- Sync
- Async
# in your playwright script, assuming the preload.js file is in same directory.
browser_context.add_init_script(path="preload.js")
# in your playwright script, assuming the preload.js file is in same directory.
await browser_context.add_init_script(path="preload.js")
The order of evaluation of multiple scripts installed via browser_context.add_init_script(**kwargs) and page.add_init_script(**kwargs) is not defined.
browser_context.background_pages
Added in: v1.11Background pages are only supported on Chromium-based browsers.
All existing background pages in the context.
browser_context.browser
Added in: v1.8Returns the browser instance of the context. If it was launched as a persistent context null gets returned.
browser_context.clear_cookies()
Added in: v1.8Clears context cookies.
browser_context.clear_permissions()
Added in: v1.8Clears all permission overrides for the browser context.
- Sync
- Async
context = browser.new_context()
context.grant_permissions(["clipboard-read"])
# do stuff ..
context.clear_permissions()
context = await browser.new_context()
await context.grant_permissions(["clipboard-read"])
# do stuff ..
context.clear_permissions()
browser_context.close()
Added in: v1.8Closes the browser context. All the pages that belong to the browser context will be closed.
The default browser context cannot be closed.
browser_context.cookies(**kwargs)
Added in: v1.8If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.
browser_context.expect_event(event, **kwargs)
Added in: v1.8event
<str> Event name, same one would pass intobrowserContext.on(event)
.#predicate
<Callable> Receives the event data and resolves to truthy value when the waiting should resolve.#timeout
<float> Maximum time to wait for in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout. The default value can be changed by using the browser_context.set_default_timeout(timeout).#- returns:EventContextManager># <
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.
- Sync
- Async
with context.expect_event("page") as event_info:
page.get_by_role("button").click()
page = event_info.value
async with context.expect_event("page") as event_info:
await page.get_by_role("button").click()
page = await event_info.value
browser_context.expect_page(**kwargs)
Added in: v1.9predicate
<Callable[Page]:bool> Receives the Page object and resolves to truthy value when the waiting should resolve.#timeout
<float> Maximum time to wait for in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout. The default value can be changed by using the browser_context.set_default_timeout(timeout).#- returns:EventContextManager[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.
browser_context.expose_binding(name, callback, **kwargs)
Added in: v1.8name
<str> Name of the function on the window object.#callback
<Callable> Callback function that will be called in the Playwright's context.#handle
<bool> 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.#- returns:NoneType># <
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(name, callback, **kwargs) for page-only version.
An example of exposing page URL to all frames in all pages in the context:
- Sync
- Async
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.get_by_role("button").click()
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright
async def run(playwright):
webkit = playwright.webkit
browser = await webkit.launch(headless=false)
context = await browser.new_context()
await context.expose_binding("pageURL", lambda source: source["page"].url)
page = await context.new_page()
await page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.pageURL();
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
await page.get_by_role("button").click()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
An example of passing an element handle:
- Sync
- Async
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>
""")
async def print(source, element):
print(await element.text_content())
await context.expose_binding("clicked", print, handle=true)
await page.set_content("""
<script>
document.addEventListener('click', event => window.clicked(event.target));
</script>
<div>Click me</div>
<div>Or click me</div>
""")
browser_context.expose_function(name, callback)
Added in: v1.8name
<str> Name of the function on the window object.#callback
<Callable> Callback function that will be called in the Playwright's context.#- returns:NoneType># <
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(name, callback) for page-only version.
An example of adding a sha256
function to all pages in the context:
- Sync
- Async
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.get_by_role("button").click()
with sync_playwright() as playwright:
run(playwright)
import asyncio
import hashlib
from playwright.async_api import async_playwright
def sha256(text):
m = hashlib.sha256()
m.update(bytes(text, "utf8"))
return m.hexdigest()
async def run(playwright):
webkit = playwright.webkit
browser = await webkit.launch(headless=False)
context = await browser.new_context()
await context.expose_function("sha256", sha256)
page = await context.new_page()
await page.set_content("""
<script>
async function onClick() {
document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');
}
</script>
<button onclick="onClick()">Click me</button>
<div></div>
""")
await page.get_by_role("button").click()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
browser_context.grant_permissions(permissions, **kwargs)
Added in: v1.8permissions
<List[str]> A permission or an array of permissions to grant. Permissions can be one of the following values:#'geolocation'
'midi'
'midi-sysex'
(system-exclusive midi)'notifications'
'camera'
'microphone'
'background-sync'
'ambient-light-sensor'
'accelerometer'
'gyroscope'
'magnetometer'
'accessibility-events'
'clipboard-read'
'clipboard-write'
'payment-handler'
origin
<str> The origin to grant permissions to, e.g. "https://example.com".#- returns:NoneType># <
Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.
browser_context.new_cdp_session(page)
Added in: v1.11page
<Page|Frame> Target to create new session for. For backwards-compatibility, this parameter is namedpage
, but it can be aPage
orFrame
type.#- returns:CDPSession># <
CDP sessions are only supported on Chromium-based browsers.
Returns the newly created session.
browser_context.new_page()
Added in: v1.8Creates a new page in the browser context.
browser_context.pages
Added in: v1.8Returns all open pages in the context.
browser_context.route(url, handler, **kwargs)
Added in: v1.8url
<str|Pattern|Callable[URL]:bool> A glob pattern, regex pattern or predicate receiving URL to match while routing. When abase_url
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.#handler
<Callable[Route, Request]> handler function to route the request.#times
<int> How often a route should be used. By default it will be used every time. Added in: v1.15#- returns:NoneType># <
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.
browser_context.route(url, handler, **kwargs) will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting browser.new_context.service_workers
to 'block'
.
An example of a naive handler that aborts all image requests:
- Sync
- Async
context = browser.new_context()
page = context.new_page()
context.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
page.goto("https://example.com")
browser.close()
context = await browser.new_context()
page = await context.new_page()
await context.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
await page.goto("https://example.com")
await browser.close()
or the same snippet using a regex pattern instead:
- Sync
- Async
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()
context = await browser.new_context()
page = await context.new_page()
await context.route(re.compile(r"(\.png$)|(\.jpg$)"), lambda route: route.abort())
page = await context.new_page()
await page.goto("https://example.com")
await 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:
- Sync
- Async
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)
def handle_route(route):
if ("my-string" in route.request.post_data)
route.fulfill(body="mocked-data")
else
route.continue_()
await context.route("/api/**", handle_route)
Page routes (set up with page.route(url, handler, **kwargs)) take precedence over browser context routes when request matches both handlers.
To remove a route with its handler you can use browser_context.unroute(url, **kwargs).
Enabling routing disables http cache.
browser_context.route_from_har(har, **kwargs)
Added in: v1.23har
<Union[str, pathlib.Path]> Path to a HAR file with prerecorded network data. Ifpath
is a relative path, then it is resolved relative to the current working directory.#not_found
<"abort"|"fallback"> 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
<bool> If specified, updates the given HAR with the actual network information instead of serving from file.#url
<str|Pattern> 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.#- <
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 browser.new_context.service_workers
to 'block'
.
browser_context.service_workers
Added in: v1.11Service workers are only supported on Chromium-based browsers.
All existing service workers in the context.
browser_context.set_default_navigation_timeout(timeout)
Added in: v1.8This setting will change the default maximum navigation time for the following methods and related shortcuts:
- page.go_back(**kwargs)
- page.go_forward(**kwargs)
- page.goto(url, **kwargs)
- page.reload(**kwargs)
- page.set_content(html, **kwargs)
- page.expect_navigation(**kwargs)
browser_context.set_default_timeout(timeout)
Added in: v1.8This setting will change the default maximum time for all the methods accepting timeout
option.
browser_context.set_extra_http_headers(headers)
Added in: v1.8headers
<Dict[str, str]> An object containing additional HTTP headers to be sent with every request. All header values must be strings.#- returns:NoneType># <
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(headers). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.
browser_context.set_extra_http_headers(headers) does not guarantee the order of headers in the outgoing requests.
browser_context.set_geolocation(geolocation)
Added in: v1.8Sets the context's geolocation. Passing null
or undefined
emulates position unavailable.
- Sync
- Async
browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667})
await browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667})
Consider using browser_context.grant_permissions(permissions, **kwargs) to grant permissions for the browser context pages to read its geolocation.
browser_context.set_offline(offline)
Added in: v1.8offline
<bool> Whether to emulate network being offline for the browser context.#- returns:NoneType># <
browser_context.storage_state(**kwargs)
Added in: v1.8path
<Union[str, pathlib.Path]> The file path to save the storage state to. Ifpath
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.#- returns:Dict># <
Returns storage state for this browser context, contains current cookies and local storage snapshot.
browser_context.unroute(url, **kwargs)
Added in: v1.8url
<str|Pattern|Callable[URL]:bool> A glob pattern, regex pattern or predicate receiving URL used to register a routing with browser_context.route(url, handler, **kwargs).#handler
<Callable[Route, Request]> Optional handler function used to register a routing with browser_context.route(url, handler, **kwargs).#- returns:NoneType># <
Removes a route created with browser_context.route(url, handler, **kwargs). When handler
is not specified, removes all routes for the url
.
browser_context.wait_for_event(event, **kwargs)
Added in: v1.8event
<str> Event name, same one typically passed into*.on(event)
.#predicate
<Callable> Receives the event data and resolves to truthy value when the waiting should resolve.#timeout
<float> Maximum time to wait for in milliseconds. Defaults to30000
(30 seconds). Pass0
to disable timeout. The default value can be changed by using the browser_context.set_default_timeout(timeout).#- returns:Any># <
In most cases, you should use browser_context.expect_event(event, **kwargs).
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.
browser_context.request
Added in: v1.16- type: <APIRequestContext>
API testing helper associated with this context. Requests made with this API will use context cookies.
browser_context.tracing
Added in: v1.12- type: <Tracing>