grafana/k6 · error
adding k6 object to new browser context: %w
Error message
adding k6 object to new browser context: %w
What it means
After a browser context or page is created, k6 injects window.k6 = { testRunId: ... } via AddInitScript (browser_mapping.go:141) so external tools such as Grafana Faro can recognize the session as automated. If that single CDP call fails, the error is wrapped as 'adding k6 object to new browser context'. This is internal plumbing, not user configuration - it indicates the context/connection broke immediately after creation or the target rejects addScriptToEvaluateOnNewDocument.
Source
Thrown at internal/js/modules/k6/browser/browser/browser_mapping.go:144
}
m["close"] = func() *sobek.Promise {
return promise(vu, func() (any, error) {
vu.untrackUserManagedBrowser(iter, b)
b.Close()
return nil, nil
})
}
}
func initBrowserContext(bctx *common.BrowserContext, testRunID string) error {
// Setting a k6 object which will contain k6 specific metadata
// on the current test run. This allows external applications
// (such as Grafana Faro) to identify that the session is a k6
// automated one and not one driven by a real person.
if err := bctx.AddInitScript(
fmt.Sprintf(`window.k6 = { testRunId: %q }`, testRunID),
); err != nil {
return fmt.Errorf("adding k6 object to new browser context: %w", err)
}
return nil
}
// parseBrowserContextOptions parses the [common.BrowserContext] options from a Sobek value.
func parseBrowserContextOptions(rt *sobek.Runtime, opts sobek.Value) (*common.BrowserContextOptions, error) {
b := common.DefaultBrowserContextOptions()
if err := mergeWith(rt, b, opts); err != nil {
return nil, err
}
if err := b.Proxy.Validate(); err != nil {
return nil, err
}
return b, nil
}
View on GitHub (pinned to 93accf6570)
Solutions
- Retry the newContext/newPage call once - the failure is usually a transient CDP race right after creation
- Check Chromium health: memory limits, version, and that no other code closes the context immediately
- If it persists on a connectOverCDP target, verify the target supports standard CDP domain methods; otherwise report it as a k6 issue with debug logs
Example fix
// before: single attempt
const ctx = await browser.newContext();
// after: one guarded retry for the transient injection race
async function newContextSafe(browser, opts) {
try {
return await browser.newContext(opts);
} catch (e) {
if (!String(e).includes('adding k6 object to new browser context')) throw e;
return await browser.newContext(opts);
}
} Defensive patterns
Strategy: retry
Try / catch
let ctx;
for (let attempt = 1; attempt <= 2; attempt++) {
try {
ctx = await browser.newContext();
break;
} catch (e) {
const transient = String(e).includes('adding k6 object to new browser context');
if (!transient || attempt === 2) throw e;
await new Promise((r) => setTimeout(r, 200)); // brief settle, then retry once
}
} Prevention
- Do not close contexts from other tasks while new contexts are being created in the same iteration
- Give containerized Chromium enough memory so it does not die mid-creation
- Enable browser debug logs (K6_BROWSER_DEBUG) when this recurs to capture the underlying CDP error
When it happens
Trigger: The CDP connection dropping or the browser crashing in the window between context creation and init-script injection; the context being closed concurrently by other code; connecting over CDP to a browser/headless shell that does not support Page.addScriptToEvaluateOnNewDocument.
Common situations: Flaky containerized Chromium under memory pressure; tests that close contexts aggressively while creating new ones; exotic CDP targets (embedded Chromium, old builds) driven via connectOverCDP.
Related errors
- can't fetch the page for unknown reason
- browser connect: %w
- querying selector %q, wrong type %T
- getting element handle for selector %q: %w
- unexpected select element type %T
AI-assisted analysis of grafana/k6@93accf6570 (2026-08-15).
Data as JSON: /api/errors/a046ef267d34c2f5.
Report an issue: GitHub.