Browser Context (upcoming)
Available in version 1.1.72 (not yet live).
Launch, quit, manage, and inspect the browser context and pages your TaskBot uses.
// @zw-run-locally
// Quick start (abridged)
await zw.browserContext.launch({
launchOptions: { headless: true },
/* More options available */
});
await zw.log("Context info", await zw.browserContext.getContextInfo());
await zw.browserContext.quit();1. Core Concepts
Launching the browser context
Launch with zw.browserContext.launch() (ZeroWork-managed). This ensures:
No-code blocks use the same context.
Lifecycle is managed for you. To opt out of auto-quit, pass
keepAlive: true.(Re)launches reapply your launch arguments.
Note: If you need a custom launch flow or a self-managed context, see Advanced: Self-managed contexts below.
Active page
A TaskBot has one active page at a time. No-code web-interaction blocks act on the active page. If you open a page in code and want no-code blocks to use it, set it with zw.browserContext.setActivePage(page).
Context (re)launch
A TaskBot automatically (re)launches a context in these cases:
Open Link building block β launches one if none exists, otherwise reuses.
Write JS set to run in the browser β launches one if none exists, otherwise reuses.
A call to
zw.browserContext.launch().Launch Browser building block β launches one and replaces the existing context.
Recovery after staleness or a crash.
Performance optimizations in long-running TaskBots.
π‘ Common gotcha: Closing the last tab (e.g., with Switch or Close Tab) ends the context. The next Open Link block creates a fresh context from defaults.
Avoid surprises (e.g., βI launched a headless browser and it suddenly became headful mid-runβ) with these best practices:
Use
zw.browserContext.launch()to launch. (If you need a custom launch flow, you can passcontextProvider.)Add cookies, scripts, and permissions via
zw.browserContext.launch()/zw.browserContext.setDefaults()so that they reapply on (re)launches. Don't use ad hoc calls likecontext.addCookies().
Persistent (sticky) profiles
Sticky profiles follow special rules.
One browser instance per profile. Same
userDataDirβ the same live browser instance across TaskBots (multiple isolated tabs).Later launches attach to the live browser instance and ignore conflicting browser-level args (e.g.,
headless). Other arguments likecookies,scriptsandonContextReadystill apply on relaunch (deduplicated).Quitting from one run closes that runβs tabs, but if other TaskBots are still using the browser instance it remains running and only quits when the last user leaves.
Lifecycle
Contexts are closed and cleared automatically.
When a run ends, the context and browser quit unless
keepAliveistrueor a shared sticky profile is still in use by other TaskBots.If
keepAliveistruebut there are no open or eligible tabs, the context and browser still quit.If a kept-alive browser remains open, the Desktop Agent cleans up when it detects manual closure (e.g., you close the window or the last tab).
β οΈ Caution:
headless: true+keepAlive: truecan leave an invisible instance consuming resources or blocking a browser profile. The UI blocks this combo, but the API allows itβuse with care.
Advanced: Self-managed contexts
Custom launch flow Provide a callback via
contextProviderinzw.browserContext.launch()when you need options the standardzwAPI doesnβt cover (e.g., launching with Firefox).Self-managed context Pass
makeMain: falseinzw.browserContext.launch()to opt out of lifecycle and relaunch policy. No-code blocks keep using the main context. To rejoin the managed flow later, usezw.browserContext.adoptContext().
2. Launch the Browser β launch()
launch()At a Glance
async
await zw.browserContext.launch(args: CustomLaunchArgs)β launches a new browser context and returns it.
Launch Arguments β CustomLaunchArgs
CustomLaunchArgs Defaults used when you pass no arguments
All options are optional. If you call zw.browserContext.launch() with no arguments, it inherits your TaskBot Run Settings and any values previously saved via zw.browserContext.setDefaults().
Context Controls β contextControls
contextControlsmaximize(default:true) Maximizes the window. Ignored inheadlessmode (headlessmust use an explicitviewport, see Context Options further below).powerMode(default:true) Hardens anti-detection and keeps TaskBots indistinguishable from human users to Cloudflare and similar anti-bot systems.βΉοΈ Trade-offs: In
powerMode, some launch and context options are unavailable (see Launch Options and Context Options further below) and file uploads larger than ~50 MB are blocked (downloads are unaffected).
persistent(default:false) Launches in a sticky browser profile. RequirespersistentProfile.userDataDir(absolute path). Multiple TaskBots with the sameuserDataDirshare the same browser instance in parallel tabs (see Persistent Profiles further below).keepAlive(default:false) Keeps the browser open after the run ends.π‘
keepAlive: trueis ignored if, at run end, no pages remain. The context then closes. Tabs on about:blank or ZeroWork launch pages donβt count unless they are tied to Write JS in-browser code execution.βΉοΈ In sticky profiles,
keepAliveapplies only to this runβs tabs. Iftrue, your tabs remain open; iffalse, your tabs close. The browser instance stays running as long as another TaskBot in the same profile is using it. It quits only when the last user leaves and no kept-alive tabs remain.β οΈ With sticky profiles, prefer leaving
keepAlivefalse. After a long device sleep, the connection can drop while the browser stays open, blocking the profile until you restart the Desktop Agent or quit that browser. Only one browser instance can use a profile at a time.
bringToFront(default:true) Brings newly opened tabs to the front (applies to no-code blocks that open tabs).
Cookies β cookies
cookiesProvide cookies up front so they are reapplied on every context (re)launch.
Each cookie must include at least name, value, and domain (and path, where relevant).
You can either provide the cookie array or, if you have cookies copied from multiple websites, an array of cookie arrays.
π‘ Tip! Avoid adding cookies in code later via
context.addCookies()β those wonβt automatically reapply on context relaunch.
Example
Scripts β scripts
scriptsScripts are injected before any page loads and reinjected on context (re)launch.
Each script item is either { path } or { content } (when using path, provide an absolute path).
π‘ Tip! Avoid adding scripts in code later via
context.addInitScript()β those wonβt automatically reapply on context relaunch.
Example
Callback when Ready β onContextReady
onContextReadyRuns whenever the context is (re)launched.
Example
Launch Options β launchOptions
launchOptionsargsUse with care: custom flags can break anti-detection. Note:--user-data-dirand--profile-directoryare reserved. In Power Mode,--remote-debugging-portis also reserved. If you pass arguments for reserved keys, they will be ignored.executablePathBy default, your Chrome path is auto-detected and used. You can override it with any Chromium-based browser (e.g., Chrome, Brave, Vivaldi, Chromium). You can find the executable path by opening chrome://version in your browser. Note: Some Chromium forks (e.g., Opera) diverge too much and may not work.headlessRuns in the background and uses fewer resources.proxyFor SOCKS5, prefix withsocks5://. SOCKS5 auth isnβt supported βusernameandpasswordapply to HTTP proxies only.More options when Power Mode is disabled When
powerModeis disabled, PlaywrightβsBrowserType.launchoptions are available. For the full list, see launch β Arguments here.
Example
Context Options β contextOptions
contextOptionspermissionsZeroWork always grants"clipboard-read"and"clipboard-write"so that the Save From Clipboard building block works.β οΈ Avoid adding permissions in code later via
context.grantPermissions()β those wonβt automatically reapply on context relaunch.
userAgentUnless you know exactly what youβre doing, prefer not to change it. If you changeuserAgent, anti-detection may no longer be fully guaranteed.viewport(default:{ width: 1440, height: 900 }) Takes effect whenmaximizeis disabled or in headless mode.More options when Power Mode is disabled When
powerModeis disabled, PlaywrightβsBrowser.newContextoptions are available. For the full list, see newContext β Arguments here.β οΈ Warning! Using Playwright API to set options like
geolocation,extraHTTPHeaders, etc. can harm the built-in anti-detection measures.
Examples
Headless with explicit viewport
Record a video
Config Options β config
configinheritDefaults(default:true) Inherits values from Run Settings and any values previously saved viazw.browserContext.setDefaults()for options you donβt specify. Example: if Run Settings have Run in background on and you donβt setheadlessinlaunchOptions,headlesswill be inherited astrue.makeMain(default:true) β advanced Iftrue, the launched context becomes the main context. The previous main context is closed (unless itskeepAlivesetting istrue). If you set tofalse, you partially lose automatic lifecycle, retries, and no-code blocks will keep using the old context.β οΈ Leave
makeMainattrueunless youβre deliberately running a self-managed context for an advanced use case. If you do, see Adopt Self-Managed Contexts for more details further below.π‘
makeMain: falseis ignored if you launch a context with a persistent (sticky) browser profile that is already launched and has already been made main. This is because launches of the same sticky browser profile all share the same browser instance, see Sticky Profiles for more details further below.
saveAsDefaults(default:trueifmakeMainistrue, otherwisefalse) β advanced Persists these options for future launches as well as automatic relaunches (e.g., after a staleness or crash recovery).β οΈ If you set
saveAsDefaultstofalse, a later relaunch may revert to older defaults. Likewise, if you setsaveAsDefaultstotruewhilemakeMainisfalse, the main context may relaunch with unexpected, unrelated settings. Prefer keeping the default.
Context Provider β contextProvider β Advanced
contextProvider β AdvancedProvide a custom launch callback. Use it when you need a custom-launched context but still want no-code blocks to use it and benefit from lifecycle management, relaunch policy, and browser profile session sharing.
Use cases
You must use a browser the ZeroWork launch API doesnβt support out of the box (for example, Firefox instead of Chromium).
You need a 100% pristine context without ZeroWorkβs built-in anti-detection measures or defaults.
Example
Launching Firefox
Because you supply the context, you control launchOptions (headless, proxy, etc.), contextOptions (viewport, permissions, etc.), window size, and any anti-detection choices. ZeroWork adopts your context, applies cookies and scripts, then runs onContextReady. Use this only if you need full control over browser creation and understand the trade-offs.
These arguments are ignored when contextProvider is set
launchOptionscontextOptionscontextControls.maximize,contextControls.powerMode
The rest of the arguments apply β including their corresponding defaults if config.inheritDefaults is true or left undefined (default is true).
β οΈ Exception: When
contextProvideris used,persistentandpersistentProfile.userDataDirare not inherited from defaults. Pass them explicitly if needed. This guardrail prevents accidental reuse or exposure of a browser profile that wasnβt launched by your context provider.π‘Sticky profiles: If you pass
persistent: truewithpersistentProfile.userDataDir, the context becomes discoverable to other TaskBots using the sameuserDataDir.
3. Defaults β setDefaults(), getDefaults()
setDefaults(), getDefaults()Defaults are the settings a TaskBot uses when launching or relaunching contexts. You can ensure that any subsequent launch or relaunch uses the settings you want by setting defaults.
See Core Concepts β Context (re)launch for a list of cases when a browser context is (re)launched.
At a Glance
async
await zw.browserContext.getDefaults()β returnsCustomLaunchArgs.async
await zw.browserContext.setDefaults(args:CustomLaunchArgs)β updates TaskBot-level default launch settings.
Notes
zw.browserContext.getDefaults()excludesconfig, which is only meaningful when launching or setting defaults.In
setDefaults(), onlyconfig.inheritDefaultsis accepted (makeMainandsaveAsDefaultsare ignored β they have no effect when setting defaults).
Examples
Set all subsequent (re)launches to headless
Discover a sticky profileβs userDataDir
4. Context β getContextInfo(), getContext()
getContextInfo(), getContext()At a Glance
zw.browserContext.getContext()β returns the current main browser context.async/sync*
await zw.browserContext.getContextInfo()β returns:
*async in browser, sync locally (see Local vs. Browser Execution).
Working with the returned context
You can call any Playwright BrowserContext API. For the full list of available methods, properties and events, see here.
β οΈ Avoid adding cookies, scripts, and permissions via the context API (e.g.,
context.addCookies()). Instead, pass them tozw.browserContext.launch()orzw.browserContext.setDefaults()(e.g.,zw.browserContext.launch({ cookies: [] })) so that they reapply on relaunch.
β οΈ Avoid changing user agent, timezone, locale, or geolocation (e.g.,
context.setGeolocation()), as this can harm the built-in anti-detection measures.
Examples
Add a listener
Clear cookies
Relaunch non-headless if the current context is headless
5. Persistent (Sticky) Browser Profiles β clearProfile(), cloneProfile()
clearProfile(), cloneProfile()Sticky profiles let multiple TaskBots share one browser session (same cookies/storage/fingerprint) via a persistent, shared userDataDir.
β οΈ Due to recent Chrome updates, you can no longer use the userDataDir of the browser profile you use for regular browsing. Instead, clone your profile with zw.browserContext.cloneProfile() or create an empty folder.
At a Glance
async
await zw.browserContext.clearProfile({ userDataDir: string })β clears the profile, or refuses to clear if the profile is in use.async
await zw.browserContext.cloneProfile({ userDataDir: string, cloneFrom: { userDataDir: string, profile: string } })β clones the profile, or refuses to clone if the target profile is in use.
Behavior
Parallel TaskBots, one instance. Same
userDataDirβ a shared browser instance (multiple isolated tabs).In-use lock. If a profile is in use, both clear and clone will fail (to avoid breaking active runs). Check via
zw.browserContext.getContextInfo().usedInTaskbots.Create & discover. ZeroWork can auto-generate sticky profiles via the Run Settings UI. You canβt create them directly via API, but you can:
Create via UI (Run Settings).
Call
zw.browserContext.getDefaults()to discover theuserDataDir.Use that path programmatically.
Shared Browser Side Effects
Non-deterministic tab order across independent TaskBots. If you need to switch programmatically, match by URL and/or TaskBot ID. Example
Attach semantics β when a browser instance is already live for that
userDataDirand a launch event attaches to it, browser-level arguments are ignored and others are applied. By default, applied items affect the whole context, so other TaskBots sharing the instance will see them (exceptkeepAliveandbringToFront, which apply to this runβs tabs only). Ignored on attach:launchOptionscontextOptionscontextControls.powerMode,contextControls.maximizecontextProvider
Applied:
contextControls.keepAlive,contextControls.bringToFrontβ apply to this run's tabs only.scriptsβ scripts that already ran are ignored; any new scripts are applied (context-wide).cookiesβ duplicate cookies by the samename+domain+pathare ignored; any new cookies are applied (context-wide).β οΈ Be careful not to pass conflicting cookies or two distinct cookies with the same
name/domain/path(duplicates will be ignored).
extraHeadersβ new headers are added (context-wide).onContextReadyβ runs on every attach (gate it if you want it to run only on true (re)launches). Gate example:
Anti-patterns
Manual and foreign instances block sharing. If you launch (manually or programmatically) your own browser with the same
userDataDiroutsidezw.browserContext.launch(), ZeroWork canβt discover or attach to it, and later TaskBots that expect to share the session will fail (only one browser instance can lock a profile at a time).If you need a custom launch flow, use
zw.browserContext.launch()withcontextProvider.If you must use a profile manually, clone it first with
zw.browserContext.cloneProfile()into an independent, non-conflicting profile.
keepAlivecaution. We donβt recommend settingkeepAlivetotrueinzw.browserContext.launch()orzw.browserContext.setDefaults()when launching sticky profiles. After a long device sleep, the connection can drop while the browser stays open, blocking the profile until you restart the Desktop Agent or quit that browser. Remember: only one browser instance can use a profile at a time. Prefer leavingkeepAlive: falsefor sticky profiles.
6. Quit Browser β quit()
quit()At a Glance
async
await zw.browserContext.quit(opts?: { forceQuit?: boolean })β closes the current context and the browser instance.
Behavior
Closes the current runβs pages and attempts to close the browser/context.
Since
zw.browserContext.quit()is called explicitly, thekeepAlivesetting is ignored.In sticky profiles:
If other TaskBots are still using the same instance, pages from this run close, but the browser instance does not quit.
If no other TaskBots are using the instance, the browser quits fully.
forceQuit: trueforces termination even if shared. Use with care.
π‘Contexts are automatically managed and closed when needed. See Core Concepts β Lifecycle. You only need to call
zw.browserContext.quit()if you need it as part of your logic, as lifecycle management is already covered.
7. Active Page & Pages β setActivePage(), getActivePage(), isActivePage(), createPage(), listPages()
setActivePage(), getActivePage(), isActivePage(), createPage(), listPages()At a Glance
async
await zw.browserContext.setActivePage(page: Page, options?: { forceContextMismatch?: boolean })β makes a Page the βactive pageβ used by no-code building blocks that do web interactions.zw.browserContext.getActivePage()β returnsPage | null, i.e. the page (if any) currently used by the TaskBot and its no-code building blocks.zw.browserContext.isActivePage(page: Page)β returnsbooleanasync
zw.browserContext.createPage({ url?: string, context?: BrowserContext })β creates a new page and returnsPagezw.browserContext.listPages()β returns:
Whatβs an active page?
The active page is the page that no-code web-interaction blocks act on. There can be only one active page at a time. You can open other pages in code, but unless you set one as active, no-code blocks wonβt use it.
Example
Notes & caveats
createPage β create in custom context β advanced
By default, pages are created in the current main context. If you need to create a page in a self-managed, non-main context, you can pass it in context, and the page will be created there instead.
Context mismatch & forceContextMismatch
If the page belongs to a different browser context than the current main context, an error is thrown similar to:
The page you provided belongs to a different browser context than the current main context. If you must use a custom launch flow, provide
contextProviderinzw.browserContext.launch(). If you must use a self-managed context, usezw.browserContext.adoptContext()to adopt it before callingzw.browserContext.setActivePage(). While not recommended, you can also setforceContextMismatchtotrue.
forceContextMismatch(default:false) β advancedConsider it an escape hatch. Setting to
trueis not recommended.If set to
true, the page is made active even if it belongs to a foreign context. No-code blocks will now operate on the active page, but inconsistencies can arise when Switch or Close Tabs is used, when a context relaunches, or when you usezw.browserContext.getContext().If you must launch a custom context, explore
contextProviderinzw.browserContext.launch()first. For more advanced use cases and self-managed contexts, explorezw.browserContext.adoptContext().
Two ways to hit a mismatch
Launching a second context with
makeMain: falseand creating a page there.Creating a context entirely outside
zw.browserContext.launch()(e.g., using the PlaywrightBrowserTypeAPI).
Bad (illustrative) pattern
8. Adopt Self-Managed Contexts (Advanced)
For advanced use cases, you can create additional (non-main), self-managed contexts via zw.browserContext.launch() and then let ZeroWork adopt it as the active, managed context.
At a Glance
async
await zw.browserContext.adoptContext(context: BrowserContext)β adopts a non-main context launched byzw.browserContext.launch()(withconfig.makeMain: false).
β οΈ Contexts created directly via the Playwright
BrowserTypeAPI are not accepted. If you need a custom launch flow, provide it viacontextProviderinzw.browserContext.launch().
Example
Switching between two launched (non-main) contexts
Notes
Largely unavailable in browser execution. The
zw.browserContext.*API is available mostly for local code execution. Only inspection methodszw.browserContext.getContextInfo()andzw.browserContext.getDefaults()are supported in the browser.
Last updated
Was this helpful?