{"record":{"id":"239291e39047a66b","repo":"grafana/k6","slug":"adding-web-vital-script-to-new-browser-context-w","errorCode":null,"errorMessage":"adding web vital script to new browser context: %w","messagePattern":"adding web vital script to new browser context: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/js/modules/k6/browser/common/browser_context.go","lineNumber":151,"sourceCode":"\tb := BrowserContext{\n\t\tBaseEventEmitter: NewBaseEventEmitter(ctx),\n\t\tctx:              ctx,\n\t\tbrowser:          browser,\n\t\tid:               id,\n\t\topts:             opts,\n\t\tlogger:           logger,\n\t\ttimeoutSettings:  NewTimeoutSettings(nil),\n\t}\n\n\tif len(opts.Permissions) > 0 {\n\t\terr := b.GrantPermissions(opts.Permissions, GrantPermissionsOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := b.AddInitScript(js.WebVitalIIFEScript); err != nil {\n\t\treturn nil, fmt.Errorf(\"adding web vital script to new browser context: %w\", err)\n\t}\n\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() {","sourceCodeStart":133,"sourceCodeEnd":169,"githubUrl":"https://github.com/grafana/k6/blob/01ffac6f245854c1b8adc6a69857c76a15f90022/internal/js/modules/k6/browser/common/browser_context.go#L133-L169","documentation":"Every new BrowserContext registers a web-vitals IIFE script via AddInitScript, which also injects it into every already-open page of the browser with Page.addScriptToEvaluateOnNewDocument. This error wraps a failure of that registration when creating the context. It cannot come from the script content (which is a constant) — it comes from the CDP calls against existing pages failing.","triggerScenarios":"Calling browser.newContext() while existing pages are in a bad state (crashed target, closed session) so evaluateOnNewDocument fails; creating a context as the browser/connection is shutting down.","commonSituations":"Opening new contexts after some pages crashed mid-run; creating contexts during teardown while k6 closes the browser; heavily loaded browsers whose page targets die concurrently.","solutions":["Create all browser contexts before heavy page churn, and avoid newContext() during teardown","Retry creating the context once after closing or stabilizing broken pages","Use K6_BROWSER_LOG=debug to see which existing page rejected the injection","Upgrade k6 — web-vital script registration has seen fixes across releases"],"exampleFix":"// before\nconst ctx2 = browser.newContext(); // while a page in ctx1 is crashing/closing\n\n// after\nawait brokenPage.close(); // stabilize first\nconst ctx2 = browser.newContext();","handlingStrategy":"retry","validationCode":"// Create contexts before page churn begins\nexport function setup() {\n  // contexts created once, up front — not mid-run while pages crash\n}","typeGuard":null,"tryCatchPattern":"try {\n  ctx = browser.newContext();\n} catch (e) {\n  if (String(e).includes('adding web vital script')) {\n    // an existing page's session rejected injection; close broken pages and retry\n    for (const p of browser.contexts().pages()) { /* close unusable pages */ }\n    ctx = browser.newContext();\n  } else throw e;\n}","preventionTips":["Create all browser contexts early, before heavy navigation workloads","Avoid newContext() during teardown","Close crashed pages instead of leaving them attached"],"tags":["cdp","browser-context","init-script","web-vitals","injection"],"backgroundTag":"init-script-injection-failed","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"}