Interface IBrowser
- Namespace
- PuppeteerSharp
- Assembly
- PuppeteerSharp.dll
Provides methods to interact with a browser.
public interface IBrowser : IDisposable, IAsyncDisposable
Examples
An example of using a IBrowser to create a IPage:
var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
var page = await browser.NewPageAsync();
await page.GoToAsync("https://example.com");
await browser.CloseAsync();
An example of disconnecting from and reconnecting to a Browser:
var browser = await Puppeteer.LaunchAsync(new LaunchOptions());
var browserWSEndpoint = browser.WebSocketEndpoint;
browser.Disconnect();
var browser2 = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = browserWSEndpoint });
await browser2.CloseAsync();
Properties
BrowserType
Returns the browser type. Chrome, Chromium or Firefox.
SupportedBrowser BrowserType { get; }
Property Value
DebugInfo
Get debug information from Puppeteer.
DebugInfo DebugInfo { get; }
Property Value
Remarks
Currently, includes pending protocol calls. In the future, more info might be added.
DefaultContext
Returns the default browser context. The default browser context can not be closed.
IBrowserContext DefaultContext { get; }
Property Value
- IBrowserContext
The default context.
DefaultWaitForTimeout
Default wait time in milliseconds. Defaults to 30 seconds.
int DefaultWaitForTimeout { get; set; }
Property Value
IsClosed
Gets a value indicating if the browser is closed.
bool IsClosed { get; }
Property Value
IsConnected
Indicates that the browser is connected.
bool IsConnected { get; }
Property Value
Process
Gets the spawned browser process. Returns null if the browser instance was created with ConnectAsync(ConnectOptions, ILoggerFactory) method.
Process Process { get; }
Property Value
Target
A target associated with the browser.
ITarget Target { get; }
Property Value
WebSocketEndpoint
Gets the Browser websocket url.
string WebSocketEndpoint { get; }
Property Value
Remarks
Browser websocket endpoint which can be used as an argument to ConnectAsync(ConnectOptions, ILoggerFactory).
The format is ws://\({host}:\){port}/devtools/browser/[id]
You can find the webSocketDebuggerUrl from http://\({host}:\){port}/json/version.
Learn more about the devtools protocol https://chromedevtools.github.io/devtools-protocol
and the browser endpoint https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target.
Methods
AddScreenAsync(AddScreenParams)
Adds a new screen with specified parameters and returns a ScreenInfo object, including the new screen's ID.
Task<ScreenInfo> AddScreenAsync(AddScreenParams @params)
Parameters
paramsAddScreenParamsThe parameters for the new screen.
Returns
- Task<ScreenInfo>
A task that resolves to the added screen information.
Remarks
Only supported in headless mode.
BrowserContexts()
Returns an array of all open IBrowserContext. In a newly created browser, this will return a single instance of IBrowserContext.
IBrowserContext[] BrowserContexts()
Returns
- IBrowserContext[]
An array of IBrowserContext objects.
ClearCustomQueryHandlers()
Clears all registered handlers.
void ClearCustomQueryHandlers()
CloseAsync()
Closes Chromium and all of its pages (if any were opened). The browser object itself is considered disposed and cannot be used anymore.
Task CloseAsync()
Returns
- Task
Task.
CreateBrowserContextAsync(BrowserContextOptions)
Creates a new browser context. This won't share cookies/cache with other browser contexts.
Task<IBrowserContext> CreateBrowserContextAsync(BrowserContextOptions options = null)
Parameters
optionsBrowserContextOptionsOptions.
Returns
- Task<IBrowserContext>
Task which resolves to a new IBrowserContext object.
Examples
using(var browser = await Puppeteer.LaunchAsync(new LaunchOptions()))
{
// Create a new browser context.
var context = await browser.CreateBrowserContextAsync();
// Create a new page in a pristine context.
var page = await context.NewPageAsync();
// Do stuff
await page.GoToAsync("https://example.com");
}
CreateCDPSessionAsync()
Creates a Chrome Devtools Protocol session attached to the browser.
Task<ICDPSession> CreateCDPSessionAsync()
Returns
- Task<ICDPSession>
A task that returns a ICDPSession.
DeleteCookieAsync(params CookieParam[])
Removes cookies from the default browser context.
Task DeleteCookieAsync(params CookieParam[] cookies)
Parameters
cookiesCookieParam[]Complete CookieParam objects to be removed.
Returns
- Task
Task.
DeleteMatchingCookiesAsync(params DeleteCookiesRequest[])
Deletes cookies matching the provided filters from the default IBrowserContext.
Task DeleteMatchingCookiesAsync(params DeleteCookiesRequest[] filters)
Parameters
filtersDeleteCookiesRequest[]Filters to match cookies against.
Returns
- Task
Task.
Disconnect()
Disconnects Puppeteer from the browser, but leaves the process running. After calling Disconnect(), the browser object is considered disposed and cannot be used anymore.
void Disconnect()
GetCookiesAsync()
Gets all cookies in the default browser context.
Task<CookieParam[]> GetCookiesAsync()
Returns
- Task<CookieParam[]>
Task which resolves to an array of CookieParam.
GetUserAgentAsync()
Gets the browser's original user agent.
Task<string> GetUserAgentAsync()
Returns
Remarks
Pages can override browser user agent with SetUserAgentAsync(string, UserAgentMetadata).
GetVersionAsync()
Gets the browser's version.
Task<string> GetVersionAsync()
Returns
- Task<string>
For headless Chromium, this is similar to
HeadlessChrome/61.0.3153.0. For non-headless, this is similar toChrome/61.0.3153.0.
Remarks
the format of GetVersionAsync() might change with future releases of Chromium.
GetWindowBoundsAsync(string)
Gets the specified window bounds.
Task<WindowBounds> GetWindowBoundsAsync(string windowId)
Parameters
windowIdstringThe window ID.
Returns
- Task<WindowBounds>
A task that resolves to the WindowBounds.
InstallExtensionAsync(string)
Installs an unpacked extension and returns the extension ID.
In Chrome, this is only available if the browser was created using pipe mode
and the --enable-unsafe-extension-debugging flag is set.
Task<string> InstallExtensionAsync(string path)
Parameters
pathstringThe path to the unpacked extension directory.
Returns
NewPageAsync(CreatePageOptions)
Creates a new page.
Task<IPage> NewPageAsync(CreatePageOptions options = null)
Parameters
optionsCreatePageOptionsOptions for creating the page.
Returns
PagesAsync(bool)
Returns a Task 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 PageAsync().
Task<IPage[]> PagesAsync(bool includeAll = false)
Parameters
includeAllboolExperimental. When true, includes all kinds of pages.
Returns
- Task<IPage[]>
Task which resolves to an array of all open pages inside the Browser. In case of multiple browser contexts, the method will return an array with all the pages in all browser contexts.
RegisterCustomQueryHandler(string, CustomQueryHandler)
Registers a custom query handler.
After registration, the handler can be used everywhere where a selector is
expected by prepending the selection string with name/. The name is
only allowed to consist of lower- and upper case latin letters.
void RegisterCustomQueryHandler(string name, CustomQueryHandler queryHandler)
Parameters
namestringThe name that the custom query handler will be registered under.
queryHandlerCustomQueryHandlerThe query handler to register.
Examples
Puppeteer.RegisterCustomQueryHandler("text", "{ … }"); var aHandle = await page.QuerySelectorAsync("text/…").
RemoveScreenAsync(string)
Removes the screen associated with the given screen ID, unless it is the primary screen.
Task RemoveScreenAsync(string screenId)
Parameters
screenIdstringThe ID of the screen to remove.
Returns
- Task
A task that completes when the screen is removed.
Remarks
Only supported in headless mode. Fails if the primary screen ID is specified.
ScreensAsync()
Gets a list of ScreenInfo objects.
Task<ScreenInfo[]> ScreensAsync()
Returns
- Task<ScreenInfo[]>
A task that resolves to an array of screen information objects.
SetCookieAsync(params CookieData[])
Sets cookies in the default browser context.
Task SetCookieAsync(params CookieData[] cookies)
Parameters
cookiesCookieData[]Cookies to set.
Returns
- Task
Task.
SetPermissionAsync(string, params PermissionEntry[])
Sets the permission for a specific origin on the default browser context.
Task SetPermissionAsync(string origin, params PermissionEntry[] permissions)
Parameters
originstringThe origin to set the permission for, e.g. "https://example.com". Use "*" for all origins (CDP only).
permissionsPermissionEntry[]The permissions to set.
Returns
- Task
The task.
SetWindowBoundsAsync(string, WindowBounds)
Sets the specified window bounds.
Task SetWindowBoundsAsync(string windowId, WindowBounds windowBounds)
Parameters
windowIdstringThe window ID.
windowBoundsWindowBoundsThe bounds to set.
Returns
- Task
A task that resolves when the bounds have been set.
Targets()
Returns An Array of all active targets.
ITarget[] Targets()
Returns
- ITarget[]
An Array of all active targets.
UninstallExtensionAsync(string)
Uninstalls a previously installed extension by its ID.
In Chrome, this is only available if the browser was created using pipe mode
and the --enable-unsafe-extension-debugging flag is set.
Task UninstallExtensionAsync(string id)
Parameters
idstringThe extension ID to uninstall.
Returns
- Task
A task that completes when the extension is uninstalled.
UnregisterCustomQueryHandler(string)
Unregister a custom query handler.
void UnregisterCustomQueryHandler(string name)
Parameters
namestringThe name of the query handler to unregistered.
WaitForTargetAsync(Func<ITarget, bool>, WaitForOptions)
This searches for a target in this specific browser context.
await page.EvaluateAsync("() => window.open('https://www.example.com/')");
var newWindowTarget = await browserContext.WaitForTargetAsync((target) => target.Url == "https://www.example.com/");
Task<ITarget> WaitForTargetAsync(Func<ITarget, bool> predicate, WaitForOptions options = null)
Parameters
predicateFunc<ITarget, bool>A function to be run for every target.
optionsWaitForOptionsoptions.
Returns
Events
Closed
Raised when the IBrowser gets closed.
event EventHandler Closed
Event Type
Disconnected
Raised when puppeteer gets disconnected from the Chromium instance. This might happen because one of the following
- Chromium is closed or crashed
- Disconnect() method was called
event EventHandler Disconnected
Event Type
TargetChanged
Raised when the url of a target changes
event EventHandler<TargetChangedArgs> TargetChanged
Event Type
TargetCreated
Raised when a target is created, for example when a new page is opened by window.open https://developer.mozilla.org/en-US/docs/Web/API/Window/open or NewPageAsync(CreatePageOptions).
event EventHandler<TargetChangedArgs> TargetCreated
Event Type
TargetDestroyed
Raised when a target is destroyed, for example when a page is closed
event EventHandler<TargetChangedArgs> TargetDestroyed
Event Type
TargetDiscovered
Raised when a target is discovered
event EventHandler<TargetChangedArgs> TargetDiscovered