feat: implement BrowserContext.closed (#10928)

This commit is contained in:
jrandolf 2023-09-18 20:11:55 +02:00 committed by GitHub
parent fd72101f7b
commit 2292078969
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 168 additions and 150 deletions

View File

@ -6,42 +6,42 @@ sidebar_label: API
## Classes ## Classes
| Class | Description | | Class | Description |
| --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Accessibility](./puppeteer.accessibility.md) | The Accessibility class provides methods for inspecting the browser's accessibility tree. The accessibility tree is used by assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Screen_reader) or [switches](https://en.wikipedia.org/wiki/Switch_access). | | [Accessibility](./puppeteer.accessibility.md) | The Accessibility class provides methods for inspecting the browser's accessibility tree. The accessibility tree is used by assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Screen_reader) or [switches](https://en.wikipedia.org/wiki/Switch_access). |
| [Browser](./puppeteer.browser.md) | <p>[Browser](./puppeteer.browser.md) represents a browser instance that is either:</p><p>- connected to via [Puppeteer.connect()](./puppeteer.puppeteer.connect.md) or - launched by [PuppeteerNode.launch()](./puppeteer.puppeteernode.launch.md).</p><p>[Browser](./puppeteer.browser.md) [emits](./puppeteer.eventemitter.md) various events which are documented in the [BrowserEvent](./puppeteer.browserevent.md) enum.</p> | | [Browser](./puppeteer.browser.md) | <p>[Browser](./puppeteer.browser.md) represents a browser instance that is either:</p><p>- connected to via [Puppeteer.connect()](./puppeteer.puppeteer.connect.md) or - launched by [PuppeteerNode.launch()](./puppeteer.puppeteernode.launch.md).</p><p>[Browser](./puppeteer.browser.md) [emits](./puppeteer.eventemitter.md) various events which are documented in the [BrowserEvent](./puppeteer.browserevent.md) enum.</p> |
| [BrowserContext](./puppeteer.browsercontext.md) | BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has a single BrowserContext used by default. The method [Browser.newPage](./puppeteer.browser.newpage.md) creates a page in the default browser context. | | [BrowserContext](./puppeteer.browsercontext.md) | <p>[BrowserContext](./puppeteer.browsercontext.md) represents individual sessions within a [browser](./puppeteer.browser.md).</p><p>When a [browser](./puppeteer.browser.md) is launched, it has a single [browser context](./puppeteer.browsercontext.md) by default. Others can be created using [Browser.createIncognitoBrowserContext()](./puppeteer.browser.createincognitobrowsercontext.md).</p><p>[BrowserContext](./puppeteer.browsercontext.md) [emits](./puppeteer.eventemitter.md) various events which are documented in the [BrowserContextEvent](./puppeteer.browsercontextevent.md) enum.</p><p>If a [page](./puppeteer.page.md) opens another [page](./puppeteer.page.md), e.g. using <code>window.open</code>, the popup will belong to the parent [page's browser context](./puppeteer.page.browsercontext.md).</p> |
| [CDPSession](./puppeteer.cdpsession.md) | The <code>CDPSession</code> instances are used to talk raw Chrome Devtools Protocol. | | [CDPSession](./puppeteer.cdpsession.md) | The <code>CDPSession</code> instances are used to talk raw Chrome Devtools Protocol. |
| [Connection](./puppeteer.connection.md) | | | [Connection](./puppeteer.connection.md) | |
| [ConsoleMessage](./puppeteer.consolemessage.md) | ConsoleMessage objects are dispatched by page via the 'console' event. | | [ConsoleMessage](./puppeteer.consolemessage.md) | ConsoleMessage objects are dispatched by page via the 'console' event. |
| [Coverage](./puppeteer.coverage.md) | The Coverage class provides methods to gather information about parts of JavaScript and CSS that were used by the page. | | [Coverage](./puppeteer.coverage.md) | The Coverage class provides methods to gather information about parts of JavaScript and CSS that were used by the page. |
| [CSSCoverage](./puppeteer.csscoverage.md) | | | [CSSCoverage](./puppeteer.csscoverage.md) | |
| [CustomError](./puppeteer.customerror.md) | | | [CustomError](./puppeteer.customerror.md) | |
| [DeviceRequestPrompt](./puppeteer.devicerequestprompt.md) | Device request prompts let you respond to the page requesting for a device through an API like WebBluetooth. | | [DeviceRequestPrompt](./puppeteer.devicerequestprompt.md) | Device request prompts let you respond to the page requesting for a device through an API like WebBluetooth. |
| [DeviceRequestPromptDevice](./puppeteer.devicerequestpromptdevice.md) | Device in a request prompt. | | [DeviceRequestPromptDevice](./puppeteer.devicerequestpromptdevice.md) | Device in a request prompt. |
| [Dialog](./puppeteer.dialog.md) | Dialog instances are dispatched by the [Page](./puppeteer.page.md) via the <code>dialog</code> event. | | [Dialog](./puppeteer.dialog.md) | Dialog instances are dispatched by the [Page](./puppeteer.page.md) via the <code>dialog</code> event. |
| [ElementHandle](./puppeteer.elementhandle.md) | ElementHandle represents an in-page DOM element. | | [ElementHandle](./puppeteer.elementhandle.md) | ElementHandle represents an in-page DOM element. |
| [EventEmitter](./puppeteer.eventemitter.md) | The EventEmitter class that many Puppeteer classes extend. | | [EventEmitter](./puppeteer.eventemitter.md) | The EventEmitter class that many Puppeteer classes extend. |
| [FileChooser](./puppeteer.filechooser.md) | File choosers let you react to the page requesting for a file. | | [FileChooser](./puppeteer.filechooser.md) | File choosers let you react to the page requesting for a file. |
| [Frame](./puppeteer.frame.md) | <p>Represents a DOM frame.</p><p>To understand frames, you can think of frames as <code>&lt;iframe&gt;</code> elements. Just like iframes, frames can be nested, and when JavaScript is executed in a frame, the JavaScript does not effect frames inside the ambient frame the JavaScript executes in.</p> | | [Frame](./puppeteer.frame.md) | <p>Represents a DOM frame.</p><p>To understand frames, you can think of frames as <code>&lt;iframe&gt;</code> elements. Just like iframes, frames can be nested, and when JavaScript is executed in a frame, the JavaScript does not effect frames inside the ambient frame the JavaScript executes in.</p> |
| [HTTPRequest](./puppeteer.httprequest.md) | Represents an HTTP request sent by a page. | | [HTTPRequest](./puppeteer.httprequest.md) | Represents an HTTP request sent by a page. |
| [HTTPResponse](./puppeteer.httpresponse.md) | The HTTPResponse class represents responses which are received by the [Page](./puppeteer.page.md) class. | | [HTTPResponse](./puppeteer.httpresponse.md) | The HTTPResponse class represents responses which are received by the [Page](./puppeteer.page.md) class. |
| [JSCoverage](./puppeteer.jscoverage.md) | | | [JSCoverage](./puppeteer.jscoverage.md) | |
| [JSHandle](./puppeteer.jshandle.md) | <p>Represents a reference to a JavaScript object. Instances can be created using [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md).</p><p>Handles prevent the referenced JavaScript object from being garbage-collected unless the handle is purposely [disposed](./puppeteer.jshandle.dispose.md). JSHandles are auto-disposed when their associated frame is navigated away or the parent context gets destroyed.</p><p>Handles can be used as arguments for any evaluation function such as [Page.$eval()](./puppeteer.page._eval.md), [Page.evaluate()](./puppeteer.page.evaluate.md), and [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md). They are resolved to their referenced object.</p> | | [JSHandle](./puppeteer.jshandle.md) | <p>Represents a reference to a JavaScript object. Instances can be created using [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md).</p><p>Handles prevent the referenced JavaScript object from being garbage-collected unless the handle is purposely [disposed](./puppeteer.jshandle.dispose.md). JSHandles are auto-disposed when their associated frame is navigated away or the parent context gets destroyed.</p><p>Handles can be used as arguments for any evaluation function such as [Page.$eval()](./puppeteer.page._eval.md), [Page.evaluate()](./puppeteer.page.evaluate.md), and [Page.evaluateHandle()](./puppeteer.page.evaluatehandle.md). They are resolved to their referenced object.</p> |
| [Keyboard](./puppeteer.keyboard.md) | Keyboard provides an api for managing a virtual keyboard. The high level api is [Keyboard.type()](./puppeteer.keyboard.type.md), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page. | | [Keyboard](./puppeteer.keyboard.md) | Keyboard provides an api for managing a virtual keyboard. The high level api is [Keyboard.type()](./puppeteer.keyboard.type.md), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page. |
| [Locator](./puppeteer.locator.md) | Locators describe a strategy of locating objects and performing an action on them. If the action fails because the object is not ready for the action, the whole operation is retried. Various preconditions for a successful action are checked automatically. | | [Locator](./puppeteer.locator.md) | Locators describe a strategy of locating objects and performing an action on them. If the action fails because the object is not ready for the action, the whole operation is retried. Various preconditions for a successful action are checked automatically. |
| [Mouse](./puppeteer.mouse.md) | The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport. | | [Mouse](./puppeteer.mouse.md) | The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport. |
| [Page](./puppeteer.page.md) | <p>Page provides methods to interact with a single tab or [extension background page](https://developer.chrome.com/extensions/background_pages) in the browser.</p><p>:::note</p><p>One Browser instance might have multiple Page instances.</p><p>:::</p> | | [Page](./puppeteer.page.md) | <p>Page provides methods to interact with a single tab or [extension background page](https://developer.chrome.com/extensions/background_pages) in the browser.</p><p>:::note</p><p>One Browser instance might have multiple Page instances.</p><p>:::</p> |
| [ProductLauncher](./puppeteer.productlauncher.md) | Describes a launcher - a class that is able to create and launch a browser instance. | | [ProductLauncher](./puppeteer.productlauncher.md) | Describes a launcher - a class that is able to create and launch a browser instance. |
| [ProtocolError](./puppeteer.protocolerror.md) | ProtocolError is emitted whenever there is an error from the protocol. | | [ProtocolError](./puppeteer.protocolerror.md) | ProtocolError is emitted whenever there is an error from the protocol. |
| [Puppeteer](./puppeteer.puppeteer.md) | <p>The main Puppeteer class.</p><p>IMPORTANT: if you are using Puppeteer in a Node environment, you will get an instance of [PuppeteerNode](./puppeteer.puppeteernode.md) when you import or require <code>puppeteer</code>. That class extends <code>Puppeteer</code>, so has all the methods documented below as well as all that are defined on [PuppeteerNode](./puppeteer.puppeteernode.md).</p> | | [Puppeteer](./puppeteer.puppeteer.md) | <p>The main Puppeteer class.</p><p>IMPORTANT: if you are using Puppeteer in a Node environment, you will get an instance of [PuppeteerNode](./puppeteer.puppeteernode.md) when you import or require <code>puppeteer</code>. That class extends <code>Puppeteer</code>, so has all the methods documented below as well as all that are defined on [PuppeteerNode](./puppeteer.puppeteernode.md).</p> |
| [PuppeteerNode](./puppeteer.puppeteernode.md) | <p>Extends the main [Puppeteer](./puppeteer.puppeteer.md) class with Node specific behaviour for fetching and downloading browsers.</p><p>If you're using Puppeteer in a Node environment, this is the class you'll get when you run <code>require('puppeteer')</code> (or the equivalent ES <code>import</code>).</p> | | [PuppeteerNode](./puppeteer.puppeteernode.md) | <p>Extends the main [Puppeteer](./puppeteer.puppeteer.md) class with Node specific behaviour for fetching and downloading browsers.</p><p>If you're using Puppeteer in a Node environment, this is the class you'll get when you run <code>require('puppeteer')</code> (or the equivalent ES <code>import</code>).</p> |
| [SecurityDetails](./puppeteer.securitydetails.md) | The SecurityDetails class represents the security details of a response that was received over a secure connection. | | [SecurityDetails](./puppeteer.securitydetails.md) | The SecurityDetails class represents the security details of a response that was received over a secure connection. |
| [Target](./puppeteer.target.md) | Target represents a [CDP target](https://chromedevtools.github.io/devtools-protocol/tot/Target/). In CDP a target is something that can be debugged such a frame, a page or a worker. | | [Target](./puppeteer.target.md) | Target represents a [CDP target](https://chromedevtools.github.io/devtools-protocol/tot/Target/). In CDP a target is something that can be debugged such a frame, a page or a worker. |
| [TimeoutError](./puppeteer.timeouterror.md) | TimeoutError is emitted whenever certain operations are terminated due to timeout. | | [TimeoutError](./puppeteer.timeouterror.md) | TimeoutError is emitted whenever certain operations are terminated due to timeout. |
| [Touchscreen](./puppeteer.touchscreen.md) | The Touchscreen class exposes touchscreen events. | | [Touchscreen](./puppeteer.touchscreen.md) | The Touchscreen class exposes touchscreen events. |
| [Tracing](./puppeteer.tracing.md) | The Tracing class exposes the tracing audit interface. | | [Tracing](./puppeteer.tracing.md) | The Tracing class exposes the tracing audit interface. |
| [WebWorker](./puppeteer.webworker.md) | This class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). | | [WebWorker](./puppeteer.webworker.md) | This class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API). |
## Enumerations ## Enumerations

View File

@ -4,13 +4,13 @@ sidebar_label: BrowserContext.browser
# BrowserContext.browser() method # BrowserContext.browser() method
The browser this browser context belongs to. Gets the [browser](./puppeteer.browser.md) associated with this [browser context](./puppeteer.browsercontext.md).
#### Signature: #### Signature:
```typescript ```typescript
class BrowserContext { class BrowserContext {
browser(): Browser; abstract browser(): Browser;
} }
``` ```

View File

@ -4,7 +4,7 @@ sidebar_label: BrowserContext.clearPermissionOverrides
# BrowserContext.clearPermissionOverrides() method # BrowserContext.clearPermissionOverrides() method
Clears all permission overrides for the browser context. Clears all permission overrides for this [browser context](./puppeteer.browsercontext.md).
#### Signature: #### Signature:
@ -20,6 +20,8 @@ Promise&lt;void&gt;
## Example ## Example
Clearing overridden permissions in the [default browser context](./puppeteer.browser.defaultbrowsercontext.md):
```ts ```ts
const context = browser.defaultBrowserContext(); const context = browser.defaultBrowserContext();
context.overridePermissions('https://example.com', ['clipboard-read']); context.overridePermissions('https://example.com', ['clipboard-read']);

View File

@ -4,13 +4,13 @@ sidebar_label: BrowserContext.close
# BrowserContext.close() method # BrowserContext.close() method
Closes the browser context. All the targets that belong to the browser context will be closed. Closes this [browser context](./puppeteer.browsercontext.md) and all associated [pages](./puppeteer.page.md).
#### Signature: #### Signature:
```typescript ```typescript
class BrowserContext { class BrowserContext {
close(): Promise<void>; abstract close(): Promise<void>;
} }
``` ```
@ -20,4 +20,4 @@ Promise&lt;void&gt;
## Remarks ## Remarks
Only incognito browser contexts can be closed. The [default browser context](./puppeteer.browser.defaultbrowsercontext.md) cannot be closed.

View File

@ -4,20 +4,18 @@ sidebar_label: BrowserContext.isIncognito
# BrowserContext.isIncognito() method # BrowserContext.isIncognito() method
Returns whether BrowserContext is incognito. The default browser context is the only non-incognito browser context. Whether this [browser context](./puppeteer.browsercontext.md) is incognito.
The [default browser context](./puppeteer.browser.defaultbrowsercontext.md) is the only non-incognito browser context.
#### Signature: #### Signature:
```typescript ```typescript
class BrowserContext { class BrowserContext {
isIncognito(): boolean; abstract isIncognito(): boolean;
} }
``` ```
**Returns:** **Returns:**
boolean boolean
## Remarks
The default browser context cannot be closed.

View File

@ -4,28 +4,30 @@ sidebar_label: BrowserContext
# BrowserContext class # BrowserContext class
BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has a single BrowserContext used by default. The method [Browser.newPage](./puppeteer.browser.newpage.md) creates a page in the default browser context. [BrowserContext](./puppeteer.browsercontext.md) represents individual sessions within a [browser](./puppeteer.browser.md).
When a [browser](./puppeteer.browser.md) is launched, it has a single [browser context](./puppeteer.browsercontext.md) by default. Others can be created using [Browser.createIncognitoBrowserContext()](./puppeteer.browser.createincognitobrowsercontext.md).
[BrowserContext](./puppeteer.browsercontext.md) [emits](./puppeteer.eventemitter.md) various events which are documented in the [BrowserContextEvent](./puppeteer.browsercontextevent.md) enum.
If a [page](./puppeteer.page.md) opens another [page](./puppeteer.page.md), e.g. using `window.open`, the popup will belong to the parent [page's browser context](./puppeteer.page.browsercontext.md).
#### Signature: #### Signature:
```typescript ```typescript
export declare class BrowserContext extends EventEmitter<BrowserContextEvents> export declare abstract class BrowserContext extends EventEmitter<BrowserContextEvents>
``` ```
**Extends:** [EventEmitter](./puppeteer.eventemitter.md)&lt;[BrowserContextEvents](./puppeteer.browsercontextevents.md)&gt; **Extends:** [EventEmitter](./puppeteer.eventemitter.md)&lt;[BrowserContextEvents](./puppeteer.browsercontextevents.md)&gt;
## Remarks ## Remarks
The Browser class extends from Puppeteer's [EventEmitter](./puppeteer.eventemitter.md) class and will emit various events which are documented in the [BrowserContextEvents](./puppeteer.browsercontextevents.md) enum.
If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser context.
Puppeteer allows creation of "incognito" browser contexts with [Browser.createIncognitoBrowserContext](./puppeteer.browser.createincognitobrowsercontext.md) method. "Incognito" browser contexts don't write any browsing data to disk.
The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the `BrowserContext` class. The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the `BrowserContext` class.
## Example ## Example
Creating an incognito [browser context](./puppeteer.browsercontext.md):
```ts ```ts
// Create a new incognito browser context // Create a new incognito browser context
const context = await browser.createIncognitoBrowserContext(); const context = await browser.createIncognitoBrowserContext();
@ -39,20 +41,21 @@ await context.close();
## Properties ## Properties
| Property | Modifiers | Type | Description | | Property | Modifiers | Type | Description |
| -------- | --------------------- | ------------------- | ----------- | | -------- | --------------------- | ------------------- | ------------------------------------------------------------------------ |
| id | <code>readonly</code> | string \| undefined | | | closed | <code>readonly</code> | boolean | Whether this [browser context](./puppeteer.browsercontext.md) is closed. |
| id | <code>readonly</code> | string \| undefined | Identifier for this [browser context](./puppeteer.browsercontext.md). |
## Methods ## Methods
| Method | Modifiers | Description | | Method | Modifiers | Description |
| --------------------------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------- | | --------------------------------------------------------------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [browser()](./puppeteer.browsercontext.browser.md) | | The browser this browser context belongs to. | | [browser()](./puppeteer.browsercontext.browser.md) | | Gets the [browser](./puppeteer.browser.md) associated with this [browser context](./puppeteer.browsercontext.md). |
| [clearPermissionOverrides()](./puppeteer.browsercontext.clearpermissionoverrides.md) | | Clears all permission overrides for the browser context. | | [clearPermissionOverrides()](./puppeteer.browsercontext.clearpermissionoverrides.md) | | Clears all permission overrides for this [browser context](./puppeteer.browsercontext.md). |
| [close()](./puppeteer.browsercontext.close.md) | | Closes the browser context. All the targets that belong to the browser context will be closed. | | [close()](./puppeteer.browsercontext.close.md) | | Closes this [browser context](./puppeteer.browsercontext.md) and all associated [pages](./puppeteer.page.md). |
| [isIncognito()](./puppeteer.browsercontext.isincognito.md) | | Returns whether BrowserContext is incognito. The default browser context is the only non-incognito browser context. | | [isIncognito()](./puppeteer.browsercontext.isincognito.md) | | <p>Whether this [browser context](./puppeteer.browsercontext.md) is incognito.</p><p>The [default browser context](./puppeteer.browser.defaultbrowsercontext.md) is the only non-incognito browser context.</p> |
| [newPage()](./puppeteer.browsercontext.newpage.md) | | Creates a new page in the browser context. | | [newPage()](./puppeteer.browsercontext.newpage.md) | | Creates a new [page](./puppeteer.page.md) in this [browser context](./puppeteer.browsercontext.md). |
| [overridePermissions(origin, permissions)](./puppeteer.browsercontext.overridepermissions.md) | | | | [overridePermissions(origin, permissions)](./puppeteer.browsercontext.overridepermissions.md) | | Grants this [browser context](./puppeteer.browsercontext.md) the given <code>permissions</code> within the given <code>origin</code>. |
| [pages()](./puppeteer.browsercontext.pages.md) | | An array of all pages inside the browser context. | | [pages()](./puppeteer.browsercontext.pages.md) | | Gets a list of all open [pages](./puppeteer.page.md) inside this [browser context](./puppeteer.browsercontext.md). |
| [targets()](./puppeteer.browsercontext.targets.md) | | An array of all active targets inside the browser context. | | [targets()](./puppeteer.browsercontext.targets.md) | | Gets all active [targets](./puppeteer.target.md) inside this [browser context](./puppeteer.browsercontext.md). |
| [waitForTarget(predicate, options)](./puppeteer.browsercontext.waitfortarget.md) | | This searches for a target in this specific browser context. | | [waitForTarget(predicate, options)](./puppeteer.browsercontext.waitfortarget.md) | | <p>Waits until a [target](./puppeteer.target.md) matching the given <code>predicate</code> appears and returns it.</p><p>This will look all open [browser contexts](./puppeteer.browsercontext.md).</p> |

View File

@ -4,13 +4,13 @@ sidebar_label: BrowserContext.newPage
# BrowserContext.newPage() method # BrowserContext.newPage() method
Creates a new page in the browser context. Creates a new [page](./puppeteer.page.md) in this [browser context](./puppeteer.browsercontext.md).
#### Signature: #### Signature:
```typescript ```typescript
class BrowserContext { class BrowserContext {
newPage(): Promise<Page>; abstract newPage(): Promise<Page>;
} }
``` ```

View File

@ -4,6 +4,8 @@ sidebar_label: BrowserContext.overridePermissions
# BrowserContext.overridePermissions() method # BrowserContext.overridePermissions() method
Grants this [browser context](./puppeteer.browsercontext.md) the given `permissions` within the given `origin`.
#### Signature: #### Signature:
```typescript ```typescript
@ -25,6 +27,8 @@ Promise&lt;void&gt;
## Example ## Example
Overriding permissions in the [default browser context](./puppeteer.browser.defaultbrowsercontext.md):
```ts ```ts
const context = browser.defaultBrowserContext(); const context = browser.defaultBrowserContext();
await context.overridePermissions('https://html5demos.com', ['geolocation']); await context.overridePermissions('https://html5demos.com', ['geolocation']);

View File

@ -4,13 +4,13 @@ sidebar_label: BrowserContext.pages
# BrowserContext.pages() method # BrowserContext.pages() method
An array of all pages inside the browser context. Gets a list of all open [pages](./puppeteer.page.md) inside this [browser context](./puppeteer.browsercontext.md).
#### Signature: #### Signature:
```typescript ```typescript
class BrowserContext { class BrowserContext {
pages(): Promise<Page[]>; abstract pages(): Promise<Page[]>;
} }
``` ```
@ -18,4 +18,6 @@ class BrowserContext {
Promise&lt;[Page](./puppeteer.page.md)\[\]&gt; Promise&lt;[Page](./puppeteer.page.md)\[\]&gt;
Promise which resolves to an array of all open pages. Non visible pages, such as `"background_page"`, will not be listed here. You can find them using [the target page](./puppeteer.target.page.md). ## Remarks
Non-visible [pages](./puppeteer.page.md), such as `"background_page"`, will not be listed here. You can find them using [Target.page()](./puppeteer.target.page.md).

View File

@ -4,7 +4,7 @@ sidebar_label: BrowserContext.targets
# BrowserContext.targets() method # BrowserContext.targets() method
An array of all active targets inside the browser context. Gets all active [targets](./puppeteer.target.md) inside this [browser context](./puppeteer.browsercontext.md).
#### Signature: #### Signature:

View File

@ -4,13 +4,15 @@ sidebar_label: BrowserContext.waitForTarget
# BrowserContext.waitForTarget() method # BrowserContext.waitForTarget() method
This searches for a target in this specific browser context. Waits until a [target](./puppeteer.target.md) matching the given `predicate` appears and returns it.
This will look all open [browser contexts](./puppeteer.browsercontext.md).
#### Signature: #### Signature:
```typescript ```typescript
class BrowserContext { class BrowserContext {
waitForTarget( abstract waitForTarget(
predicate: (x: Target) => boolean | Promise<boolean>, predicate: (x: Target) => boolean | Promise<boolean>,
options?: { options?: {
timeout?: number; timeout?: number;
@ -21,20 +23,18 @@ class BrowserContext {
## Parameters ## Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------- | ---------------------------------------------------------------------------- | ------------ |
| predicate | (x: [Target](./puppeteer.target.md)) =&gt; boolean \| Promise&lt;boolean&gt; | A function to be run for every target | | predicate | (x: [Target](./puppeteer.target.md)) =&gt; boolean \| Promise&lt;boolean&gt; | |
| options | { timeout?: number; } | _(Optional)_ An object of options. Accepts a timeout, which is the maximum wait time in milliseconds. Pass <code>0</code> to disable the timeout. Defaults to 30 seconds. | | options | { timeout?: number; } | _(Optional)_ |
**Returns:** **Returns:**
Promise&lt;[Target](./puppeteer.target.md)&gt; Promise&lt;[Target](./puppeteer.target.md)&gt;
Promise which resolves to the first target found that matches the `predicate` function.
## Example ## Example
An example of finding a target for a page opened via `window.open`: Finding a target for a page opened via `window.open`:
```ts ```ts
await page.evaluate(() => window.open('https://www.example.com/')); await page.evaluate(() => window.open('https://www.example.com/'));

View File

@ -15,6 +15,7 @@
*/ */
import {EventEmitter, type EventType} from '../common/EventEmitter.js'; import {EventEmitter, type EventType} from '../common/EventEmitter.js';
import {debugError} from '../common/util.js';
import type {Browser, Permission} from './Browser.js'; import type {Browser, Permission} from './Browser.js';
import {type Page} from './Page.js'; import {type Page} from './Page.js';
@ -63,25 +64,21 @@ export interface BrowserContextEvents extends Record<EventType, unknown> {
} }
/** /**
* BrowserContexts provide a way to operate multiple independent browser * {@link BrowserContext} represents individual sessions within a
* sessions. When a browser is launched, it has a single BrowserContext used by * {@link Browser | browser}.
* default. The method {@link Browser.newPage | Browser.newPage} creates a page
* in the default browser context.
* *
* @remarks * When a {@link Browser | browser} is launched, it has a single
* {@link BrowserContext | browser context} by default. Others can be created
* using {@link Browser.createIncognitoBrowserContext}.
* *
* The Browser class extends from Puppeteer's {@link EventEmitter} class and * {@link BrowserContext} {@link EventEmitter | emits} various events which are
* will emit various events which are documented in the * documented in the {@link BrowserContextEvent} enum.
* {@link BrowserContextEvents} enum.
* *
* If a page opens another page, e.g. with a `window.open` call, the popup will * If a {@link Page | page} opens another {@link Page | page}, e.g. using
* belong to the parent page's browser context. * `window.open`, the popup will belong to the parent {@link Page.browserContext
* | page's browser context}.
* *
* Puppeteer allows creation of "incognito" browser contexts with * @example Creating an incognito {@link BrowserContext | browser context}:
* {@link Browser.createIncognitoBrowserContext | Browser.createIncognitoBrowserContext}
* method. "Incognito" browser contexts don't write any browsing data to disk.
*
* @example
* *
* ```ts * ```ts
* // Create a new incognito browser context * // Create a new incognito browser context
@ -97,7 +94,7 @@ export interface BrowserContextEvents extends Record<EventType, unknown> {
* @public * @public
*/ */
export class BrowserContext extends EventEmitter<BrowserContextEvents> { export abstract class BrowserContext extends EventEmitter<BrowserContextEvents> {
/** /**
* @internal * @internal
*/ */
@ -106,17 +103,20 @@ export class BrowserContext extends EventEmitter<BrowserContextEvents> {
} }
/** /**
* An array of all active targets inside the browser context. * Gets all active {@link Target | targets} inside this
* {@link BrowserContext | browser context}.
*/ */
targets(): Target[] { targets(): Target[] {
throw new Error('Not implemented'); throw new Error('Not implemented');
} }
/** /**
* This searches for a target in this specific browser context. * Waits until a {@link Target | target} matching the given `predicate`
* appears and returns it.
* *
* @example * This will look all open {@link BrowserContext | browser contexts}.
* An example of finding a target for a page opened via `window.open`: *
* @example Finding a target for a page opened via `window.open`:
* *
* ```ts * ```ts
* await page.evaluate(() => window.open('https://www.example.com/')); * await page.evaluate(() => window.open('https://www.example.com/'));
@ -124,46 +124,35 @@ export class BrowserContext extends EventEmitter<BrowserContextEvents> {
* target => target.url() === 'https://www.example.com/' * target => target.url() === 'https://www.example.com/'
* ); * );
* ``` * ```
*
* @param predicate - A function to be run for every target
* @param options - An object of options. Accepts a timeout,
* which is the maximum wait time in milliseconds.
* Pass `0` to disable the timeout. Defaults to 30 seconds.
* @returns Promise which resolves to the first target found
* that matches the `predicate` function.
*/ */
waitForTarget( abstract waitForTarget(
predicate: (x: Target) => boolean | Promise<boolean>, predicate: (x: Target) => boolean | Promise<boolean>,
options?: {timeout?: number} options?: {timeout?: number}
): Promise<Target>; ): Promise<Target>;
waitForTarget(): Promise<Target> {
throw new Error('Not implemented');
}
/** /**
* An array of all pages inside the browser context. * Gets a list of all open {@link Page | pages} inside this
* {@link BrowserContext | browser context}.
* *
* @returns Promise which resolves to an array of all open pages. * @remarks Non-visible {@link Page | pages}, such as `"background_page"`,
* Non visible pages, such as `"background_page"`, will not be listed here. * will not be listed here. You can find them using {@link Target.page}.
* You can find them using {@link Target.page | the target page}.
*/ */
pages(): Promise<Page[]> { abstract pages(): Promise<Page[]>;
throw new Error('Not implemented');
}
/** /**
* Returns whether BrowserContext is incognito. * Whether this {@link BrowserContext | browser context} is incognito.
* The default browser context is the only non-incognito browser context.
* *
* @remarks * The {@link Browser.defaultBrowserContext | default browser context} is the
* The default browser context cannot be closed. * only non-incognito browser context.
*/ */
isIncognito(): boolean { abstract isIncognito(): boolean;
throw new Error('Not implemented');
}
/** /**
* @example * Grants this {@link BrowserContext | browser context} the given
* `permissions` within the given `origin`.
*
* @example Overriding permissions in the
* {@link Browser.defaultBrowserContext | default browser context}:
* *
* ```ts * ```ts
* const context = browser.defaultBrowserContext(); * const context = browser.defaultBrowserContext();
@ -172,9 +161,10 @@ export class BrowserContext extends EventEmitter<BrowserContextEvents> {
* ]); * ]);
* ``` * ```
* *
* @param origin - The origin to grant permissions to, e.g. "https://example.com". * @param origin - The origin to grant permissions to, e.g.
* @param permissions - An array of permissions to grant. * "https://example.com".
* All permissions that are not listed here will be automatically denied. * @param permissions - An array of permissions to grant. All permissions that
* are not listed here will be automatically denied.
*/ */
overridePermissions(origin: string, permissions: Permission[]): Promise<void>; overridePermissions(origin: string, permissions: Permission[]): Promise<void>;
overridePermissions(): Promise<void> { overridePermissions(): Promise<void> {
@ -182,9 +172,11 @@ export class BrowserContext extends EventEmitter<BrowserContextEvents> {
} }
/** /**
* Clears all permission overrides for the browser context. * Clears all permission overrides for this
* {@link BrowserContext | browser context}.
* *
* @example * @example Clearing overridden permissions in the
* {@link Browser.defaultBrowserContext | default browser context}:
* *
* ```ts * ```ts
* const context = browser.defaultBrowserContext(); * const context = browser.defaultBrowserContext();
@ -198,31 +190,48 @@ export class BrowserContext extends EventEmitter<BrowserContextEvents> {
} }
/** /**
* Creates a new page in the browser context. * Creates a new {@link Page | page} in this
* {@link BrowserContext | browser context}.
*/ */
newPage(): Promise<Page> { abstract newPage(): Promise<Page>;
throw new Error('Not implemented');
}
/** /**
* The browser this browser context belongs to. * Gets the {@link Browser | browser} associated with this
* {@link BrowserContext | browser context}.
*/ */
browser(): Browser { abstract browser(): Browser;
throw new Error('Not implemented');
}
/** /**
* Closes the browser context. All the targets that belong to the browser context * Closes this {@link BrowserContext | browser context} and all associated
* will be closed. * {@link Page | pages}.
* *
* @remarks * @remarks The
* Only incognito browser contexts can be closed. * {@link Browser.defaultBrowserContext | default browser context} cannot be
* closed.
*/ */
close(): Promise<void> { abstract close(): Promise<void>;
throw new Error('Not implemented');
/**
* Whether this {@link BrowserContext | browser context} is closed.
*/
get closed(): boolean {
return !this.browser().browserContexts().includes(this);
} }
/**
* Identifier for this {@link BrowserContext | browser context}.
*/
get id(): string | undefined { get id(): string | undefined {
return undefined; return undefined;
} }
/** @internal */
[Symbol.dispose](): void {
return void this.close().catch(debugError);
}
/** @internal */
[Symbol.asyncDispose](): Promise<void> {
return this.close();
}
} }