PuppeteerSharp

Introduction

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.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using PuppeteerSharp;

public class Program
{
    public static async Task Main(string[] args)
    {
        var serverUrl = "https://production.cloudbrowser.ai/api/v1/Browser/Open";
        var apiToken = "your-api-token"; // Replace with your actual API token

        try
        {
            // Create HttpClient and include the API token in the request headers
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);

            // Fetch the WebSocket debugger URL using the API token
            var browserWSEndpoint = await httpClient.GetStringAsync(serverUrl);

            // Connect to the remote browser using PuppeteerSharp
            var browser = await Puppeteer.ConnectAsync(new ConnectOptions
            {
                BrowserWSEndpoint = browserWSEndpoint
            });

            // Open a new page and navigate to a URL
            var page = await browser.NewPageAsync();
            await page.GoToAsync("https://ifconfig.me");

            // Get and log the page title
            var title = await page.GetTitleAsync();
            Console.WriteLine($"Page title: {title}");

            // Close the browser
            await browser.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.

var browser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = browserWSEndpoint });

Create a New Page: Open a new page in the browser.

var page = await browser.NewPageAsync();

Navigate and Interact: Navigate to a URL and perform actions like retrieving the page title.

await page.GoToAsync("https://ifconfig.me"); 
var title = await page.GetTitleAsync(); 
Console.WriteLine($"Page title: {title}");

Close the Browser: Close the browser after operations are complete.

await browser.CloseAsync();

Error Handling

  • HTTP Request Errors: Handle errors when fetching the WebSocket URL by checking the response and catching exceptions.

  • Connection Errors: Catch and log errors that occur during connection to the remote browser or during navigation.

Last updated