Browser automation has traditionally been used for UI testing, scraping, and repetitive browser tasks. AI agents introduce a different use case: allowing an application to decide which browser actions are required and execute those actions through controlled tools.
A browser agent might receive a request such as:
"Open the customer portal, find the latest invoice,
and download it."
Instead of implementing a fixed sequence of browser commands, an agent can reason about the task, choose available browser tools, inspect the current page, and continue through multiple steps.
The architecture is powerful, but it also introduces new risks. A browser agent can navigate to unexpected pages, click the wrong control, submit forms, or interact with sensitive information.
For that reason, a production browser agent should not simply connect an LLM to unrestricted browser automation. It should combine Playwright, .NET, tool boundaries, validation, permissions, and observability.
This article shows how to build the foundation of such a system.
What Is a Browser Automation Agent?
A traditional Playwright workflow is deterministic:
Open Browser
|
Navigate to URL
|
Find Element
|
Click
|
Fill Form
|
Submit
A browser automation agent introduces a decision layer:
User Goal
|
v
AI Agent
|
+----> Browser Tool
|
+----> Page Inspection
|
+----> Navigation
|
+----> Click / Fill
|
v
Task Result
The agent decides what to do next based on the current state of the browser.
This distinction is important.
Playwright provides browser control. The AI agent provides task-level decision making.
Playwright's .NET library exposes browser automation APIs for Chromium, Firefox, and WebKit, making it a useful foundation for implementing browser tools in a .NET application.
Why Use Playwright for Browser Agents?
Playwright provides several capabilities that are useful when building controlled browser automation:
Browser and context management
Page navigation
Locators
Element interaction
Screenshots
Network interception
Multiple browser engines
Automatic waiting around many interactions
Support for asynchronous .NET APIs
A deterministic Playwright operation might look like:
await page.GotoAsync("https://example.com");
await page.GetByRole(
AriaRole.Button,
new() { Name = "Sign in" })
.ClickAsync();
The challenge for an agent is deciding which page to open, which element to interact with, and whether the requested action is safe.
That is where the architecture becomes more important than the individual Playwright calls.
High-Level Architecture
A production-oriented browser agent can be divided into several layers:
+----------------------+
| User / Application |
+----------+-----------+
|
v
+----------------------+
| Agent Orchestrator |
+----------+-----------+
|
v
+----------------------+
| Tool Policy Layer |
+----------+-----------+
|
+-----+-----+
| |
v v
Browser Tools Read Tools
|
v
+----------------------+
| Playwright Runtime |
+----------+-----------+
|
v
Web Site
The policy layer is especially important.
The agent should not receive unrestricted access to every browser API.
Instead, expose a small set of well-defined tools.
Creating a .NET Project
Create a console application:
dotnet new console -n BrowserAgent
cd BrowserAgent
dotnet add package Microsoft.Playwright
Build the project:
dotnet build
Then install the Playwright browser binaries using the Playwright tooling appropriate to your project and operating environment.
Keep the Playwright package version pinned in production so that browser automation behavior is reproducible.
Launching a Browser
A basic Playwright setup looks like this:
using Microsoft.Playwright;
using var playwright = await Playwright.CreateAsync();
await using var browser =
await playwright.Chromium.LaunchAsync(
new BrowserTypeLaunchOptions
{
Headless = true
});
var page = await browser.NewPageAsync();
await page.GotoAsync("https://example.com");
Console.WriteLine(await page.TitleAsync());
For an agent, browser initialization should normally be handled by a dedicated service rather than recreated independently for every tool call.
Creating a Browser Service
Create an abstraction around Playwright:
public interface IBrowserService
{
Task NavigateAsync(
string url,
CancellationToken cancellationToken);
Task<string> GetPageTextAsync(
CancellationToken cancellationToken);
Task ClickAsync(
string selector,
CancellationToken cancellationToken);
Task FillAsync(
string selector,
string value,
CancellationToken cancellationToken);
}
Then implement it with Playwright:
public sealed class PlaywrightBrowserService
: IBrowserService
{
private readonly IPage _page;
public PlaywrightBrowserService(IPage page)
{
_page = page;
}
public async Task NavigateAsync(
string url,
CancellationToken cancellationToken)
{
await _page.GotoAsync(
url,
new PageGotoOptions
{
WaitUntil = WaitUntilState.DOMContentLoaded
});
}
public async Task<string> GetPageTextAsync(
CancellationToken cancellationToken)
{
return await _page.Locator("body")
.InnerTextAsync();
}
public Task ClickAsync(
string selector,
CancellationToken cancellationToken)
{
return _page.Locator(selector).ClickAsync();
}
public Task FillAsync(
string selector,
string value,
CancellationToken cancellationToken)
{
return _page.Locator(selector).FillAsync(value);
}
}
The abstraction gives the agent access to browser capabilities without exposing the entire Playwright API.
Why Tool Boundaries Matter
It may be tempting to expose a generic function such as:
ExecuteJavaScript(code)
That creates a very large security boundary.
A better design exposes narrowly scoped tools:
navigate
get_page_text
find_element
click
fill
take_screenshot
download_file
The agent can then operate within an explicit capability set.
For example:
public sealed record BrowserToolPolicy(
bool AllowNavigation,
bool AllowClick,
bool AllowFormInput,
bool AllowDownloads);
The policy can be evaluated before every tool invocation.
Creating Agent Tools
A browser agent needs tools that describe browser actions in language the model can understand.
A navigation tool might accept:
{
"url": "https://example.com"
}
A click tool might accept:
{
"target": "Sign in button"
}
A form tool might accept:
{
"field": "Email",
"value": "[email protected]"
}
The tool implementation is responsible for converting these high-level requests into safe Playwright operations.
Do not allow the model to construct arbitrary CSS or JavaScript unless the application explicitly requires it and the security model supports it.
Prefer Semantic Locators
When possible, use Playwright's semantic locator APIs.
For example:
await page.GetByRole(
AriaRole.Button,
new() { Name = "Continue" })
.ClickAsync();
This is generally easier to understand and maintain than a deeply nested CSS selector.
A browser agent also benefits from semantic descriptions because the tool can expose meaningful targets such as:
Button: Continue
Link: View invoice
Textbox: Email
Heading: Account Overview
rather than exposing the complete DOM.
Page State as Agent Context
An agent needs enough information about the current page to make its next decision.
A basic page-state object might be:
public sealed record BrowserState(
string Url,
string Title,
string VisibleText);
You can collect it with Playwright:
public async Task<BrowserState> GetStateAsync(
IPage page)
{
return new BrowserState(
page.Url,
await page.TitleAsync(),
await page.Locator("body").InnerTextAsync());
}
In production, sending the entire page text to an LLM can be inefficient and may expose sensitive information.
A better approach is to construct a compact representation containing only the information required for the next decision.
The Agent Loop
A simplified agent loop looks like this:
1. Receive goal
2. Inspect browser state
3. Ask model for next action
4. Validate requested action
5. Execute Playwright tool
6. Capture resulting state
7. Repeat until completed
In pseudocode:
while (!taskCompleted)
{
var state = await browser.GetStateAsync();
var action = await agent.DecideAsync(
goal,
state);
policy.Validate(action);
await tools.ExecuteAsync(action);
}
The loop needs a hard execution limit.
For example:
const int MaxSteps = 20;
for (var step = 0; step < MaxSteps; step++)
{
// Inspect, decide, validate and execute.
}
Without a limit, an agent can become trapped in repeated navigation or retry behavior.
Handling Authentication
Authentication is one of the most sensitive parts of browser automation.
Avoid giving the model direct access to passwords.
Instead, authentication should be handled by application-controlled infrastructure.
For example:
Application
|
v
Authenticated Browser Context
|
v
Agent
The agent can operate within an already authenticated context without receiving the underlying credentials.
Playwright browser contexts can also help isolate sessions.
For multi-user systems, each task should receive the appropriate isolated browser context rather than sharing one global session.
Session Isolation
A browser context can provide a separate environment for a task:
var context =
await browser.NewContextAsync();
var page =
await context.NewPageAsync();
This is useful when multiple users or tasks are processed concurrently.
The architecture should avoid accidentally sharing:
Cookies
Local storage
Session state
Authentication tokens
Download directories
between unrelated users.
Handling Downloads
Suppose an agent needs to download an invoice.
A controlled tool might look like:
var downloadTask =
page.WaitForDownloadAsync();
await page.GetByRole(
AriaRole.Link,
new() { Name = "Download Invoice" })
.ClickAsync();
var download = await downloadTask;
await download.SaveAsAsync(
Path.Combine(
outputDirectory,
download.SuggestedFilename));
The download destination should be controlled by the application.
Do not allow the model to arbitrarily choose filesystem paths.
Join the conversation! Your thoughts help the community grow.