{"record":{"id":"f50c2c70cba8abb8","repo":"grafana/k6","slug":"adding-init-script-to-browser-context-w","errorCode":null,"errorMessage":"adding init script to browser context: %w","messagePattern":"adding init script to browser context: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/js/modules/k6/browser/common/browser_context.go","lineNumber":171,"sourceCode":"\tif err := b.AddInitScript(js.WebVitalInitScript); err != nil {\n\t\treturn nil, fmt.Errorf(\"adding web vital init script to new browser context: %w\", err)\n\t}\n\tif err := b.setDownloadsPath(opts.DownloadsPath); err != nil {\n\t\treturn nil, fmt.Errorf(\"setting downloads path: %w\", err)\n\t}\n\n\treturn &b, nil\n}\n\n// AddInitScript adds a script that will be initialized on all new pages.\nfunc (b *BrowserContext) AddInitScript(script string) error {\n\tb.logger.Debugf(\"BrowserContext:AddInitScript\", \"bctxid:%v\", b.id)\n\n\tb.evaluateOnNewDocumentSources = append(b.evaluateOnNewDocumentSources, script)\n\n\tfor _, p := range b.browser.getPages() {\n\t\tif err := p.evaluateOnNewDocument(script); err != nil {\n\t\t\treturn fmt.Errorf(\"adding init script to browser context: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (b *BrowserContext) applyAllInitScripts(p *Page) error {\n\tfor _, source := range b.evaluateOnNewDocumentSources {\n\t\tif err := p.evaluateOnNewDocument(source); err != nil {\n\t\t\treturn fmt.Errorf(\"adding init script to browser context: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Browser returns the browser instance that this browser context belongs to.\nfunc (b *BrowserContext) Browser() *Browser {","sourceCodeStart":153,"sourceCodeEnd":189,"githubUrl":"https://github.com/grafana/k6/blob/01ffac6f245854c1b8adc6a69857c76a15f90022/internal/js/modules/k6/browser/common/browser_context.go#L153-L189","documentation":"Thrown by BrowserContext.AddInitScript: the script was recorded on the context, but replaying it onto one of the ALREADY-OPEN pages failed. The per-page call is the CDP command Page.addScriptToEvaluateOnNewDocument, and the %w chain carries the underlying CDP or transport error. Note the script is still stored in b.evaluateOnNewDocumentSources, so future pages will get it; only the failing existing page is left without it.","triggerScenarios":"Calling browserContext.addInitScript(script) after pages were already created in that context, while at least one page's CDP session is broken: a page closed concurrently by another iteration, its target crashed, or the WebSocket to Chromium dropped.","commonSituations":"Scripts that add init hooks between iterations while earlier iterations' pages are still closing; sharing one browser context across parallel VU iterations; Chromium killed by the OS (OOM) or crashing during teardown; calling addInitScript inside a helper that runs late in the page lifecycle.","solutions":["Call addInitScript immediately after browser.newContext(), before any newPage() call, so the per-page loop iterates over nothing","If pages exist, make sure they are alive and not being closed concurrently (await your page.close() calls) before adding the script","Use a fresh browserContext per iteration/VU so no half-dead pages accumulate in the context","Check the wrapped error: if the browser process died, restart the browser/browser option rather than retrying the same context","Upgrade k6 — older builds had races between page teardown and context-level operations"],"exampleFix":"// before\nconst ctx = browser.newContext();\nconst page = ctx.newPage();\n// ... later, page may be closing/crashed\nctx.addInitScript('window.flag = true'); // can fail on existing pages\n\n// after\nconst ctx = browser.newContext();\nctx.addInitScript('window.flag = true'); // no pages yet, nothing to replay onto\nconst page = ctx.newPage();","handlingStrategy":"try-catch","validationCode":"// register init scripts before any page exists, so the per-page replay loop is empty\nconst ctx = browser.newContext();\nctx.addInitScript('window.flag = true'); // no pages yet -> cannot fail per-page\nconst page = ctx.newPage();","typeGuard":null,"tryCatchPattern":"try {\n  ctx.addInitScript(script);\n} catch (e) {\n  if (String(e.message).includes('adding init script')) {\n    // existing page session is dead: recreate context (script is re-registered) and new pages\n    console.warn(`init script replay failed: ${e.message}`);\n  } else {\n    throw e;\n  }\n}","preventionTips":["Always call addInitScript immediately after newContext, before newPage","Use one browserContext per iteration instead of sharing across VUs","Fully await page.close() before any later context-level mutation"],"tags":["browser","cdp","init-script","browser-context"],"backgroundTag":"cdp-protocol-error","analyzedSha":"01ffac6f245854c1b8adc6a69857c76a15f90022","analyzedAt":"2026-08-18T03:05:52.393Z","contentChangedAt":"2026-08-18T03:05:52.393Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}