This guide provides a step-by-step example of how to connect to a remote browser using the PuppeteerSharp library for C#. It includes instructions on how to use an API token for authentication when connecting to CloudBrowser.
Prerequisites
.NET SDK: Ensure the .NET SDK is installed on your system.
PuppeteerSharp Library: Install PuppeteerSharp via NuGet.
API Token: Your unique API token for authenticating requests to CloudBrowser.
Example Code
The following code demonstrates how to connect to a remote browser using PuppeteerSharp, retrieve the WebSocket endpoint with an API token, and perform basic navigation.
usingSystem;usingSystem.Net.Http;usingSystem.Net.Http.Headers;usingSystem.Threading.Tasks;usingPuppeteerSharp;publicclassProgram{publicstaticasyncTaskMain(string[] args) {var serverUrl ="https://production.cloudbrowser.ai/api/v1/Browser/Open";var apiToken ="your-api-token"; // Replace with your actual API tokentry { // Create HttpClient and include the API token in the request headersvar httpClient =newHttpClient();httpClient.DefaultRequestHeaders.Authorization=newAuthenticationHeaderValue("Bearer", apiToken); // Fetch the WebSocket debugger URL using the API tokenvar browserWSEndpoint =awaithttpClient.GetStringAsync(serverUrl); // Connect to the remote browser using PuppeteerSharpvar browser =awaitPuppeteer.ConnectAsync(newConnectOptions { BrowserWSEndpoint = browserWSEndpoint }); // Open a new page and navigate to a URLvar page =awaitbrowser.NewPageAsync();awaitpage.GoToAsync("https://ifconfig.me"); // Get and log the page titlevar title =awaitpage.GetTitleAsync();Console.WriteLine($"Page title: {title}"); // Close the browserawaitbrowser.CloseAsync(); }catch (Exception ex) {Console.WriteLine($"Error connecting to remote browser: {ex.Message}"); } }}
Code Explanation
Import Required Namespaces: Import necessary namespaces for HTTP operations and PuppeteerSharp.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using PuppeteerSharp;
Define Variables: Set the CloudBrowser API URL and your API token.
var serverUrl = "https://production.cloudbrowser.ai/api/v1/Browser/Open";
var apiToken = "your-api-token"; // Replace with your actual API token
Create HttpClient with Authorization: Initialize an HttpClient and set the Authorization header to include the API token.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
Fetch WebSocket URL: Send a GET request to the CloudBrowser API to retrieve the WebSocket URL, including the API token in the request headers.
var browserWSEndpoint = await httpClient.GetStringAsync(serverUrl);
Connect to the Browser: Use PuppeteerSharp’s ConnectAsync method with the WebSocket URL to connect to the remote browser.