You can set a custom User-Agent string for remote browsers. This allows you to emulate different browsers, devices, or operating systems, which is useful for testing, web scraping, or accessing content optimized for specific platforms.
Configuring a Custom User-Agent
The User-Agent must be set when launching the browser, affecting all pages opened by that browser instance. Below are the steps to configure a custom User-Agent.
1. Configure the Custom User-Agent for the Browser
Here is a C# example showing how to configure and use a custom User-Agent with a browser managed by CloudBrowser.
usingSystem;usingSystem.Net.Http;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 token // Define the custom User-Agentvar userAgent ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"; // Replace with your desired User-Agent // Create an HttpClient and include the API token in the request headersvar httpClient =newHttpClient();httpClient.DefaultRequestHeaders.Authorization=newAuthenticationHeaderValue("Bearer", apiToken); // Request the WebSocket endpoint of the remote browservar browserWSEndpoint =awaithttpClient.GetStringAsync(serverUrl); // Connect to the remote browservar browser =awaitPuppeteer.ConnectAsync(newConnectOptions { BrowserWSEndpoint = browserWSEndpoint }); // Create a new pagevar page =awaitbrowser.NewPageAsync(); // Set the custom User-Agentawaitpage.SetUserAgentAsync(userAgent); // Navigate to a URL to verify the User-Agentawaitpage.GoToAsync("https://www.whatismybrowser.com/"); // Close the browserawaitbrowser.CloseAsync(); }}
2. Code Explanation
Define the Custom User-Agent: Set the userAgent variable with the desired User-Agent string.
var userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"; // Replace with your desired User-Agent
Connect to the Server: Get the WebSocket endpoint for the browser from the CloudBrowser API.
var httpClient = new HttpClient();
var browserWSEndpoint = await httpClient.GetStringAsync(serverUrl);
Connect to the Remote Browser: Use Puppeteer.ConnectAsync to connect to the browser.