How to Set a Custom User Agent in Playwright
Set a custom user agent in a Playwright browser context or Playwright Test, with runnable examples, troubleshooting tips, and guidance on what the override changes.
Set userAgent when you create a Playwright browser context, before opening pages in it. In Playwright Test, configure it with test.use({ userAgent: '...' }). A user-agent override changes the value sent as the browser’s user-agent; by itself, it does not configure every other browser or device characteristic.
Set a user agent in a Playwright script
Pass the string to browser.newContext(). Create pages from that context so they use its configuration:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext({
userAgent: 'ExampleAutomation/1.0 (compatible; MyTest/1.0)',
});
try {
const page = await context.newPage();
await page.goto('https://example.com');
console.log(await page.title());
} finally {
await context.close();
await browser.close();
}
})();
Save this as user-agent.cjs, install Playwright with npm install playwright, and run node user-agent.cjs. Replace the example string with the exact value your test needs. The context option is documented in the BrowserType API; the emulation guide shows the same configuration pattern.
Set a user agent in Playwright Test
Use test.use() to set the option for tests in a file or a describe block:
import { test, expect } from '@playwright/test';
test.use({
userAgent: 'ExampleAutomation/1.0 (compatible; MyTest/1.0)',
});
test('loads the home page', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle(/Example Domain/);
});
Save it as a Playwright Test file, such as tests/user-agent.spec.ts, then run it with npx playwright test tests/user-agent.spec.ts. For a single test group, put test.use() inside test.describe() so the setting is scoped to that group. The official emulation guide documents this approach.
Choose the right approach
| Approach | Use it when |
|---|---|
browser.newContext({ userAgent }) |
You are writing a Playwright library script and want the setting scoped to that context. |
test.use({ userAgent }) |
You are configuring tests with Playwright Test. |
| A Playwright device descriptor | You need broader device emulation. Playwright’s documentation says the user agent is included in the device descriptor. |
Playwright’s guidance is that the user agent is included in a device descriptor and is rarely something users need to change. If you only need a different user-agent value, override userAgent. If you need a device setup, start with a descriptor and adjust relevant context options. Do not assume that changing the string alone reproduces a particular browser, operating system, or device. See the official emulation guidance.
Configuration details and edge cases
- Set it on the context before opening pages. Pages created from the configured context use its settings. If you already have a context, create a new one with the desired option and open the page there.
- Keep contexts isolated by scenario. Use separate contexts when tests need different user agents; this makes each configuration explicit.
- Use the exact value under test. A typo or unintended whitespace can make a server-side user-agent check behave differently from the case you intended to cover.
- Do not treat it as full impersonation. The documented option sets the context’s user-agent value. It does not claim to change all other browser signals or device characteristics.
- Prefer the device descriptor for device emulation. Playwright notes that the descriptor includes a user agent, along with the broader device configuration.
Verify the value your test sends
When a test depends on server-side user-agent handling, verify the request received by a server or test endpoint you control. A page’s JavaScript-visible properties can help inspect browser behavior, but they are not a substitute for checking the request header when that header is what your application uses.
For repeatable tests, record the context configuration alongside the test case and use a controlled endpoint or local test server. Avoid relying on a third-party site to echo request details because its behavior and availability can change independently of your test.
Troubleshooting
| Symptom | Likely cause | What to do |
|---|---|---|
| The site still appears to receive the default user agent. | The option was set on a different context, or the page was opened before the configured context was created. | Create the context with userAgent first, then create the page from that context. Check that the tested request is made by that page. |
| Some browser or device checks still identify the original environment. | A user-agent string is only one context setting; it does not establish complete device emulation. | Use a Playwright device descriptor when broader emulation is needed, and configure any additional context options relevant to the test. |
| Playwright Test reports a configuration or type error. | The option may be placed outside the supported test configuration, or the project may not be using Playwright Test. | Use test.use({ userAgent: '...' }) in a Playwright Test file. For a library script, use browser.newContext({ userAgent: '...' }). |
| Different tests send different values unexpectedly. | Configuration is scoped differently than intended, or tests share assumptions about context setup. | Put the setting at the intended file or describe scope, or create an explicit context for each library-script scenario. |
Performance, reliability, and cost
Setting this option is a context configuration choice; the cited Playwright documentation does not publish a performance benchmark or a special cost for using it. For reliability, keep the value and context setup explicit, use a controlled endpoint for verification, and avoid depending on unrelated sites to reflect a request header. Browser execution still has the ordinary runtime and infrastructure costs of your Playwright setup.
Or skip the browser setup
If your goal is a screenshot rather than testing a custom user-agent value in your own browser automation, ScreenshotNeo provides a website screenshot API and MCP server. Its API supports custom user-agent configuration along with headers, cookies, and other capture options; see the ScreenshotNeo API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));
- Cookie banners are accepted and removed before capture; newsletter popups and chat widgets are removed too. Each cleanup step can be turned off.
- Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing. Responses identify the page verdict and billing status in headers.
- An MCP server gives AI agents tools for screenshots, page information, and PDF capture.
- The free plan includes 1,000 screenshots a month with no card. Paid plans start at $5 for 3,000 screenshots.
Sign up for ScreenshotNeo and get 1,000 screenshots a month free, with no card.
FAQ
Can I change the user agent after creating a page?
Configure it when creating the browser context, then create the page from that context. For another value, create a context with the new setting.
Does changing the user agent make a browser test equivalent to a mobile device?
No. The override sets the user-agent value. Use a device descriptor and relevant context settings for broader device emulation.
Should every test use a custom user agent?
No. Playwright says the user agent is already included in device descriptors and is rarely something users need to change. Override it when a test specifically needs a different value.


