Setting cookies

Introduction

You can set cookies to customize browser sessions for various use cases, including authenticated sessions, tracking, and testing. This feature helps you simulate different user sessions by configuring cookies programmatically.

Configuring Cookies

Cookies can be set on a page after the browser instance is launched and before navigating to the target URL. Below are the steps to configure cookies.

1. Set Cookies for the Browser Session

Here is a C# example showing how to set cookies in a browser managed by CloudBrowser.

using System;
using System.Net.Http;
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

        // Define the cookies
        var cookies = new CookieParam[]
        {
            new CookieParam { Name = "example_cookie", Value = "cookie_value", Domain = "example.com" },
            new CookieParam { Name = "session_id", Value = "123456", Domain = "example.com" }
        };

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

        // Request the WebSocket endpoint of the remote browser
        var browserWSEndpoint = await httpClient.GetStringAsync(serverUrl);

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

        // Create a new page
        var page = await browser.NewPageAsync();

        // Set cookies
        await page.SetCookieAsync(cookies);

        // Navigate to a URL to verify the cookies
        await page.GoToAsync("https://www.cloudbrowser.ai");

        // Close the browser
        await browser.CloseAsync();
    }
}

2. Code Explanation

  1. Define the Cookies: Create an array of CookieParam objects with the cookie details you want to set.

   var cookies = new CookieParam[]
   {
       new CookieParam { Name = "example_cookie", Value = "cookie_value", Domain = "example.com" },
       new CookieParam { Name = "session_id", Value = "123456", Domain = "example.com" }
   };
  1. Request the WebSocket Endpoint: Use HttpClient to send a GET request to the server URL to obtain the WebSocket endpoint.

   var httpClient = new HttpClient();
   var browserWSEndpoint = await httpClient.GetStringAsync(serverUrl);
  1. Connect to the Remote Browser: Use Puppeteer.ConnectAsync to connect to the browser using the obtained WebSocket endpoint.

   var browser = await Puppeteer.ConnectAsync(new ConnectOptions
   {
       BrowserWSEndpoint = browserWSEndpoint
   });
  1. Create a New Page: Create a new page instance in the browser.

   var page = await browser.NewPageAsync();
  1. Set Cookies: Use page.SetCookieAsync to set the defined cookies on the page.

   await page.SetCookieAsync(cookies);
  1. Navigate and Verify: Navigate to the target site to verify that the cookies are set.

   await page.GoToAsync("https://example.com");
  1. Close the Browser: Close the browser when finished.

   await browser.CloseAsync();

Additional Considerations

  • Cookie Attributes: Ensure that the cookie attributes like Domain, Path, and Expires are set correctly according to your requirements.

  • Secure and HttpOnly Flags: Be aware of Secure and HttpOnly flags on cookies which affect their scope and security.

  • Error Handling: Implement error handling to capture and manage potential issues when setting cookies or connecting to the browser.

Last updated