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.
2. Code Explanation
Define the Cookies: Create an array of
CookieParam
objects with the cookie details you want to set.
Request the WebSocket Endpoint: Use
HttpClient
to send a GET request to the server URL to obtain the WebSocket endpoint.
Connect to the Remote Browser: Use
Puppeteer.ConnectAsync
to connect to the browser using the obtained WebSocket endpoint.
Create a New Page: Create a new page instance in the browser.
Set Cookies: Use
page.SetCookieAsync
to set the defined cookies on the page.
Navigate and Verify: Navigate to the target site to verify that the cookies are set.
Close the Browser: Close the browser when finished.
Additional Considerations
Cookie Attributes: Ensure that the cookie attributes like
Domain
,Path
, andExpires
are set correctly according to your requirements.Secure and HttpOnly Flags: Be aware of
Secure
andHttpOnly
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