Get
The following example demonstrates how to request a browser instance, navigate to a webpage, disconnect the browser, retrieve details about all active browsers, and close them.
using BrowserService svc = new("YOUR CLOUDBROWSER.AI TOKEN");
// Request a new browser instance
var rp = await svc.Open().ConfigureAwait(false);
if (rp.Status == ResponseStatus.Succes) {
Console.WriteLine("Browser requested");
} else {
Console.WriteLine("Error requesting browser: {0}", rp.Status.ToString());
return;
}
// Connect to the browser using PuppeteerSharp
var browser = await Puppeteer.ConnectAsync(new () {
BrowserWSEndpoint = rp.Address,
DefaultViewport = null,
AcceptInsecureCerts = true,
SlowMo = 0
}).ConfigureAwait(continueOnCapturedContext: false);
Console.WriteLine("Browser connected");
// Navigate to a webpage
var page = (await browser.PagesAsync().ConfigureAwait(false))[0];
await page.GoToAsync("http://www.cloudbrowser.ai").ConfigureAwait(false);
Console.WriteLine("Web visited");
// Disconnect the browser
browser.Disconnect();
Console.WriteLine("Browser disconnected");
// Retrieve the list of all active browsers
var rpGet = await svc.Get().ConfigureAwait(false);
// Print details of all active browsers
Console.WriteLine("Label | Address | Started On | VNC Opened | VNC Pass");
foreach (var b in rpGet.Browsers) {
Console.WriteLine("{0} | {1} | {2} | {3} | {4}", b.Label, b.Address, b.StartedOn, b.VNCPass != null, b.VNCPass);
await svc.Close(b.Address).ConfigureAwait(false); // Close each browser
}
Full example
How It Works
Initialize the Client: Create an instance of
BrowserService
using your API token.Request a Browser Instance: Call
svc.Open()
to request a new browser session. The response will contain a WebSocket address (rp.Address
) to connect to the browser instance.Connect to the Browser with Puppeteer: Use PuppeteerSharp to connect to the browser instance using the WebSocket address provided by the
Open
method.Navigate to a Webpage: Interact with the browser by navigating to a specified URL (e.g., "http://www.cloudbrowser.ai").
Disconnect the Browser: Use
browser.Disconnect()
to disconnect from the browser session via PuppeteerSharp.Retrieve Active Browsers: Call
svc.Get()
to get a list of all active browser sessions, including their details like label, address, start time, and VNC credentials.Close Active Browsers: Loop through the list of active browsers and close each one by calling
svc.Close()
for each browser's address.
This approach allows you to automate browser interaction, retrieve information about active sessions, and close them as needed, all through the CloudBrowser.AI API.
Last updated