{"record":{"id":"a046ef267d34c2f5","repo":"grafana/k6","slug":"adding-k6-object-to-new-browser-context-w","errorCode":null,"errorMessage":"adding k6 object to new browser context: %w","messagePattern":"adding k6 object to new browser context: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/js/modules/k6/browser/browser/browser_mapping.go","lineNumber":144,"sourceCode":"\t}\n\tm[\"close\"] = func() *sobek.Promise {\n\t\treturn promise(vu, func() (any, error) {\n\t\t\tvu.untrackUserManagedBrowser(iter, b)\n\t\t\tb.Close()\n\t\t\treturn nil, nil\n\t\t})\n\t}\n}\n\nfunc initBrowserContext(bctx *common.BrowserContext, testRunID string) error {\n\t// Setting a k6 object which will contain k6 specific metadata\n\t// on the current test run. This allows external applications\n\t// (such as Grafana Faro) to identify that the session is a k6\n\t// automated one and not one driven by a real person.\n\tif err := bctx.AddInitScript(\n\t\tfmt.Sprintf(`window.k6 = { testRunId: %q }`, testRunID),\n\t); err != nil {\n\t\treturn fmt.Errorf(\"adding k6 object to new browser context: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// parseBrowserContextOptions parses the [common.BrowserContext] options from a Sobek value.\nfunc parseBrowserContextOptions(rt *sobek.Runtime, opts sobek.Value) (*common.BrowserContextOptions, error) {\n\tb := common.DefaultBrowserContextOptions()\n\tif err := mergeWith(rt, b, opts); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := b.Proxy.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}\n","sourceCodeStart":126,"sourceCodeEnd":161,"githubUrl":"https://github.com/grafana/k6/blob/93accf6570dcd306ca5e99cc44c393ee3797761b/internal/js/modules/k6/browser/browser/browser_mapping.go#L126-L161","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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"],"exampleFix":"// before: single attempt\nconst ctx = await browser.newContext();\n\n// after: one guarded retry for the transient injection race\nasync function newContextSafe(browser, opts) {\n  try {\n    return await browser.newContext(opts);\n  } catch (e) {\n    if (!String(e).includes('adding k6 object to new browser context')) throw e;\n    return await browser.newContext(opts);\n  }\n}","handlingStrategy":"retry","validationCode":null,"typeGuard":null,"tryCatchPattern":"let ctx;\nfor (let attempt = 1; attempt <= 2; attempt++) {\n  try {\n    ctx = await browser.newContext();\n    break;\n  } catch (e) {\n    const transient = String(e).includes('adding k6 object to new browser context');\n    if (!transient || attempt === 2) throw e;\n    await new Promise((r) => setTimeout(r, 200)); // brief settle, then retry once\n  }\n}","preventionTips":["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"],"tags":["browser","browser-context","cdp","internal","transient"],"backgroundTag":null,"analyzedSha":"93accf6570dcd306ca5e99cc44c393ee3797761b","analyzedAt":"2026-08-15T21:23:27.118Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}