A context groups pages that share an environment, cookies and storage. Configure it before opening its first page; keep using your framework's Page, Locator and navigation methods afterward. Start with SDK installation if you do not have a session yet.
Choose how the environment is owned
An ordinary context uses the automation framework's usual options. For example, session.newContext() returns a real Playwright BrowserContext, and its ordinary emulation settings remain mutable. In Node, framework context options belong under framework; Python accepts them as normal keyword arguments.
A managed context gives Mimic ownership of a coherent environment profile. Choose it when related observations—viewport, screen, locale, preferences, fonts and graphics—must come from one validated configuration. In Node and Python, supplying profile or proxy selects this mode. A proxy without an explicit profile generates one. Media or resource policy alone does not change an ordinary context into a managed identity.
Managed environments are immutable. Configure identity in the profile; creating a new context is the supported way to change its viewport or identity. Combining a managed profile with framework emulation such as viewport, userAgent, locale,timezoneId or colorScheme is rejected. Later CDP identity mutations return profileLocked. Request interception and injected scripts can still alter observations; profile ownership is not a security sandbox.
Create a managed context
These complete examples generate an environment, install a resource policy in observation-only mode, and then create a page. All configuration finishes before the context is returned. A validation failure disposes the newly created context and surfaces the error.
JavaScript / TypeScript · Playwright
Save as contexts.mjs, then run node contexts.mjs.
import { launch } from "mimic-browser/playwright";
const session = await launch();
try {
const context = await session.newContext({
profile: { generate: { seed: "demo-account" } },
resourcePolicy: {
reportOnly: true,
presets: ["noSpeculativeLoads"],
budgets: { maxRequests: 100, maxConcurrent: 8 },
},
});
try {
const page = await context.newPage();
await page.setContent("<h1>One coherent environment</h1>");
console.log(await page.evaluate(() => ({
language: navigator.language,
viewport: [innerWidth, innerHeight],
userAgent: navigator.userAgent,
})));
} finally {
await context.close();
}
} finally {
await session.close();
}Python · synchronous Playwright
Save as contexts.py, then run python contexts.py.
from mimic.playwright.sync_api import launch
from mimic.generated import (
GenerateProfileOptions,
GenerateProfileSelection,
ResourceBudgets,
ResourcePolicy,
)
with launch() as session:
context = session.new_context(
profile=GenerateProfileSelection(
generate=GenerateProfileOptions(seed="demo-account")
),
resource_policy=ResourcePolicy(
report_only=True,
presets=["noSpeculativeLoads"],
budgets=ResourceBudgets(max_requests=100, max_concurrent=8),
),
)
try:
page = context.new_page()
page.set_content("<h1>One coherent environment</h1>")
print(page.evaluate("""() => ({
language: navigator.language,
viewport: [innerWidth, innerHeight],
userAgent: navigator.userAgent
})"""))
finally:
context.close()For async code, import from mimic.playwright.async_api, await launch() and context/page operations, and use async with for the session.
C# · Playwright
With mimic-browser.Playwright installed, replace Program.cs and run dotnet run. The explicitly named NewConfiguredContextAsync helper selects managed mode.
using Mimic.Playwright;
using System.Text.Json.Nodes;
await using var session = await PlaywrightSession.LaunchAsync();
var configuration = new JsonObject
{
["profile"] = new JsonObject
{
["generate"] = new JsonObject { ["seed"] = "demo-account" }
},
["resourcePolicy"] = new JsonObject
{
["reportOnly"] = true,
["presets"] = new JsonArray("noSpeculativeLoads")
}
};
var context = await session.NewConfiguredContextAsync(configuration);
try
{
var page = await context.NewPageAsync();
await page.SetContentAsync("<h1>One coherent environment</h1>");
Console.WriteLine(await page.Locator("h1").TextContentAsync());
}
finally
{
await context.CloseAsync();
}Browser selection in a generated profile describes the installed observation bundle: browser: "chrome", version: 152 and platform: "windows". It does not download a different browser or select the Mimic runtime release. Omitting the seed generates a random one; an empty seed, unknown fields, nulls and unsupported selectors fail.
Save and restore a profile
A profile token is a portable string, not a server-side registry entry. Generate a token, export its descriptor as JSON, and import that descriptor to validate it before creating another context. The example below writes mimic-profile.json and restores it in the same session; keep that file to import in a later session.
import { readFile, writeFile } from "node:fs/promises";
import { launch } from "mimic-browser/playwright";
const session = await launch();
try {
const generated = await session.mimic.generateProfile({ seed: "demo-account" });
const exported = await session.mimic.exportProfile({ profile: generated.profile });
await writeFile("mimic-profile.json", JSON.stringify(exported.profile, null, 2));
const descriptor = JSON.parse(await readFile("mimic-profile.json", "utf8"));
const restored = await session.mimic.importProfile({ profile: descriptor });
console.log("Profile:", restored.profileId, "Warnings:", restored.warnings);
const context = await session.newContext({ profile: restored.profile });
try {
const page = await context.newPage();
await page.setContent("<h1>Restored environment</h1>");
console.log(await page.locator("h1").textContent());
} finally {
await context.close();
}
} finally {
await session.close();
}Generate, import and export allocate no context or page. Tokens contain the environment, not cookies, storage, proxy credentials or media source bindings. Import checks the installed base and resolved environment; unavailable or changed data returns incompatibleProfile. A seed alone does not guarantee identical output across releases. Different seeds can produce the same profileId, and different profiles do not guarantee different GPUs or public IP addresses.
Make deliberate manual changes
Pass a manual environment to session.mimic.importProfile with mode: "manual", then pass its returned profile token to the context helper. This JSON is the import command's argument; it is not a context configuration or CLI profile file.
{
"mode": "manual",
"profile": {
"hardware": { "logicalProcessors": 8, "deviceMemoryGB": 8 },
"locale": {
"languages": ["en-US", "en"],
"intlLocale": "en-US",
"timezone": "America/New_York"
},
"preferences": { "colorScheme": "dark", "reducedMotion": false }
}
}Named fields merge into the installed baseline; arrays replace complete arrays. Known invalid values and cross-field conflicts are rejected. Returned warnings explain limits of validation rather than bypassing it. Browser and network identity retain the installed baseline. Graphics/fonts must retain the baseline or match one complete supported recipe; editing individual renderer/font fields or mixing recipes is rejected. Custom timezone and Intl locale require V8's native Intl support.
To edit an exported descriptor, take its environment member and import that through manual mode. Do not rewrite its hash.getProfile reports effective observations; its result is not accepted as context-creation input.
Route a context through a proxy
The context-level proxy accepts server,username and password. HTTP, HTTPS and SOCKS5 endpoints are supported. Keep credentials in separate fields instead of URL userinfo; load real credentials from your application's configuration. The following shape goes beside profile in context settings.
{
"server": "http://127.0.0.1:8080",
"username": "proxy-user",
"password": "proxy-password"
}A failed proxy does not fall back to a direct request, and proxy mode disables HTTP/3. HTTP(S) resource loads and Worker fetch use the context's proxy. A timezone or language does not infer the proxy's geography. ICE metadata does not establish UDP/WebRTC routing. Profile reads and errors omit proxy credentials. The runtime installer has separate proxy/network settings: a browser context proxy does not route SDK downloads.
Control resource work explicitly
A resource policy belongs to one context and its pages, frames, workers and WebSockets. Without a policy, the ordinary compatibility path remains in effect. Start with reportOnly: true to observe the proposed decisions before changing a workload's behavior.
{
"reportOnly": true,
"rules": [
{
"id": "skip-images-and-fonts",
"match": { "kinds": ["image", "font"] },
"work": { "cacheRead": false, "network": false }
}
],
"budgets": {
"maxRequests": 100,
"maxConcurrent": 8,
"maxResponseBytes": 8388608,
"maxBodyBytes": 33554432,
"maxRetainedBytes": 16777216
}
}Rules run in order; the first match wins. Explicit rules precede presets. A resource kind reflects why a request was made:fetch("photo.png") is a Fetch request, not an image request. The example would deny image/font cache reads and network acquisitions; report-only mode records the decision while delivering ordinary results.
Policy fields, presets and budget behavior
| Setting | Effect |
|---|---|
noVisualAssets, dataExtraction | Deny cache reads and network acquisition for image, font, media and favicon kinds. |
noSpeculativeLoads | Deny preload and prefetch mechanisms. |
headersOnly | Admit status/headers but stop response bodies. It is unsuitable for ordinary page navigation that needs HTML. |
match | Select kinds, hosts, exact HTTP origins, URL glob, owner, mechanism or top-level site. Leading-dot hosts match subdomains; schemeful top-level sites use the registrable domain. |
cacheRead, network | With cache reads allowed and network disabled, a cache hit succeeds and a miss fails. Redirect targets are checked again. |
body, prefixBytes | Choose full, none or prefix; prefix requires a positive byte count. Partial Fetch bodies error on consumption, including clones. They are not cached or retained for CDP body retrieval. |
decode: false | For images, retain intrinsic metadata where available and deny later pixel materialization. It is a fidelity tradeoff. |
cacheRetain, debugRetain | Control HTTP-cache and CDP response-body retention separately. |
maxRequests, maxConcurrent | Limit network acquisitions, not cache hits. |
maxResponseBytes, maxBodyBytes | Limit individual response size and cumulative body-reader/cache-copy bytes. These do not cap transport buffering. |
maxDecodedBytes, maxRetainedBytes | Bound cumulative logical image pixel work and retained response-body storage. They are not process memory limits. |
Budget zero means unlimited. A nonzero maxWireBytes is unsupported and rejected. Timers, animations and scheduler behavior do not change. Blocking fonts, images, scripts or bodies changes observable behavior and needs workload-specific validation.
Mimic.updateResourcePolicy takes { browserContextId, policy } and publishes an atomic update. In-flight loads and redirects keep their captured policy generation; an update does not cancel them or clear caches.Mimic.getResourcePolicyStats requires the explicit context ID. Its body-read and known-avoided-byte counters are not a claim of exact wire traffic saved. See the command reference.
Configure capture before opening a page
A context helper accepts a media configuration or a media factory. The factory receives the owning context ID and the session's Mimic command client, so it can discover private capture sources for that exact context. It finishes before the helper returns a context for user pages. Failure closes the context. The media catalog remains separate from the saved environment token.
Source selection, public camera/microphone identity and site permission are separate decisions. Discovery/configuration does not open capture or grant permission. Use the camera and microphone guide for complete recipes and track cleanup.
Own and close your contexts
Close a context when its job finishes, even if its last page is already closed. Page closure alone does not dispose context storage. Context helpers track what they create; if you create a context directly through the native framework, manage that handle's lifetime yourself.
Closing a launched SDK session closes its contexts, disconnects its clients and stops its owned runtime. Closing a connected session cleans up its own contexts and connections while preserving the external runtime and other clients' contexts. Keep separate accounts in separate contexts; limit the number of live contexts when processing many jobs.
Use the helper your framework supports
| Integration | Context entry point |
|---|---|
| Node Playwright / Puppeteer | newContext(settings); native options live under framework. Returns the framework's BrowserContext. |
| Python Playwright / Pyppeteer | new_context(profile=..., proxy=..., resource_policy=..., media=...). Async helpers await creation and factories. |
| C# Playwright / PuppeteerSharp | NewContextAsync for ordinary contexts, media and policy; NewConfiguredContextAsync explicitly selects managed configuration. Factories use mediaFactory. |
| Java / Kotlin Playwright | newContext for ordinary configuration; newConfiguredContext for managed profiles. Uses Playwright Java's native BrowserContext. |
| Go Rod | NewContext or NewConfiguredContext; the native Rod Browser handle represents the context. The configured media variant is NewConfiguredContextWithMedia. |
| Go chromedp | LaunchConfigured / ConnectConfigured configure the session's context before its initial target. The media variants end in WithMedia. |
| Rust chromiumoxide | new_context(ConfigureContextParams) returns the native BrowserContextId; leave its input context ID empty. new_context_with_media accepts the factory. |
| Ruby Ferrum | new_context accepts profile, proxy, resource_policy and media keywords; returns a Ferrum Context. |
| PHP chrome-php | newContext returns a Mimic context handle because the framework has no Context class. newPage($context) returns a real Chrome PHP Page. |
Generated command models follow each language's naming conventions. Context IDs are explicit command arguments, not inferred from an ambient current page. Continue with types and commands or runtime installation and ownership.