RemoteDesktop

The following example demonstrates how to request a browser instance, connect to it via Puppeteer, start a remote desktop session, and then stop the remote desktop session.

using BrowserService svc = new("YOUR CLOUDBROWSER.AI TOKEN");

var rp = await svc.Open().ConfigureAwait(false);

if (rp.Status == CloudBrowserAiSharp.Browser.Types.ResponseStatus.Succes) {
    Console.WriteLine("Browser requested");
} else {
    Console.WriteLine("Error requesting browser: {0}", rp.Status.ToString());
    return;
}

var browser = await Puppeteer.ConnectAsync(new() {
    BrowserWSEndpoint = rp.Address,
    DefaultViewport = null,
    AcceptInsecureCerts = true,
    SlowMo = 0
}).ConfigureAwait(continueOnCapturedContext: false);
Console.WriteLine("Browser connected");

// Start the remote desktop session
var rmt = await svc.StartRemoteDesktop(rp.Address).ConfigureAwait(false);
Console.WriteLine("Remote desktop address:");
Console.WriteLine($"https://browser.cloudbrowser.ai${ObtainId(rp.Address)}/{rmt.Password}");

// Wait for 5 seconds to simulate the usage of the remote desktop
await Task.Delay(5000).ConfigureAwait(false);

// Stop the remote desktop session
await svc.StopRemoteDesktop(rp.Address).ConfigureAwait(false);
Console.WriteLine("Remote Desktop closed");
}

// Function to extract the ID from the browser WebSocket address
static string ObtainId(string address) {
string pattern = @"\.ai\/(.*?)\/devtools";
var match1 = Regex.Match(address, pattern);
return match1.Groups[1].Value;
}

Full example

How It Works

  1. Initialize the Client: Create an instance of BrowserService using your API token.

  2. Request a Browser Instance: Call svc.Open() to request a new browser session. This will return a WebSocket address to connect to the browser instance.

  3. Connect to the Browser with Puppeteer: Use PuppeteerSharp to connect to the browser instance using the provided WebSocket endpoint (rp.Address).

  4. Start Remote Desktop Session: Call svc.StartRemoteDesktop() to initiate a remote desktop session, and the service will return a URL and password to access the session.

  5. Obtain Remote Desktop URL: The URL to access the remote desktop is generated by extracting the browser ID from the WebSocket address and appending the password provided by StartRemoteDesktop().

  6. Stop Remote Desktop Session: Call svc.StopRemoteDesktop() to close the remote desktop session once you're done.

  7. Wait for Remote Desktop Use: After starting the remote desktop session, the program waits for a set period (5 seconds) to simulate usage before closing the session.


This approach allows you to remotely control a browser instance and interact with it via a remote desktop session, making it useful for automating tasks where visual interaction with the browser is necessary.

Last updated