{"record":{"id":"220e439eb08f81f3","repo":"grafana/k6","slug":"internal-error-while-applying-init-scripts-to-page","errorCode":null,"errorMessage":"internal error while applying init scripts to page: %w","messagePattern":"internal error while applying init scripts to page: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/js/modules/k6/browser/common/page.go","lineNumber":363,"sourceCode":"\tp.frameSessions[cdp.FrameID(tid)] = p.mainFrameSession\n\tp.frameSessionsMu.Unlock()\n\tp.Mouse = NewMouse(ctx, s, p.frameManager.MainFrame(), bctx.timeoutSettings, p.Keyboard)\n\tp.Touchscreen = NewTouchscreen(ctx, s, p.Keyboard)\n\n\tp.initEvents()\n\n\taction := target.SetAutoAttach(true, true).WithFlatten(true)\n\tif err := action.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil {\n\t\treturn nil, fmt.Errorf(\"internal error while auto attaching to browser pages: %w\", err)\n\t}\n\n\tadd := runtime.AddBinding(webVitalBinding)\n\tif err := add.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil {\n\t\treturn nil, fmt.Errorf(\"internal error while adding binding to page: %w\", err)\n\t}\n\n\tif err := bctx.applyAllInitScripts(&p); err != nil {\n\t\treturn nil, fmt.Errorf(\"internal error while applying init scripts to page: %w\", err)\n\t}\n\n\treturn &p, nil\n}\n\nfunc (p *Page) initEvents() {\n\tp.logger.Debugf(\"Page:initEvents\",\n\t\t\"sid:%v tid:%v\", p.session.ID(), p.targetID)\n\n\tevents := []string{\n\t\tcdproto.EventRuntimeConsoleAPICalled,\n\t}\n\tp.session.on(p.ctx, events, p.eventCh)\n\n\tgo func() {\n\t\tp.logger.Debugf(\"Page:initEvents:go\",\n\t\t\t\"sid:%v tid:%v\", p.session.ID(), p.targetID)\n\t\tdefer func() {","sourceCodeStart":345,"sourceCodeEnd":381,"githubUrl":"https://github.com/grafana/k6/blob/93accf6570dcd306ca5e99cc44c393ee3797761b/internal/js/modules/k6/browser/common/page.go#L345-L381","documentation":"During page creation, applying the context's init scripts (Page.addScriptToEvaluateOnNewDocument for each script added with addInitScript) failed on the new page's session. This is the third of the page-init CDP calls; it fails for the same infrastructural reasons as SetAutoAttach/AddBinding — the session is dead or dying.","triggerScenarios":"browser.newPage() after ctx.addInitScript(...) while the browser connection is broken, the browser crashed, or the target is being destroyed concurrently (close racing creation).","commonSituations":"Init scripts that assume a live target but creation races teardown; long tests where the browser died earlier; heavy page churn at iteration end.","solutions":["Look upstream for the root session failure in the logs and address it","Keep addInitScript + newPage sequences at the start of the iteration, away from close()","Verify the script source is a plain string (it is registered as-is; syntax errors in it fail later at runtime, but oversized/binary content can also break the CDP call)","If persistent, upgrade k6 / verify the chromium binary version"],"exampleFix":"// before\nconst ctx = browser.newContext();\nawait ctx.close();\nctx.addInitScript('window.foo = 1');\nconst page = await ctx.newPage(); // applying init scripts on dead context\n\n// after\nconst ctx = browser.newContext();\nctx.addInitScript('window.foo = 1');\nconst page = await ctx.newPage(); // init scripts applied while alive\nawait page.goto('https://test.k6.io/');","handlingStrategy":"retry","validationCode":"const ctx = browser.newContext();\nctx.addInitScript('window.marker = 1;'); // register before any page exists\nconst page = await ctx.newPage();","typeGuard":null,"tryCatchPattern":"try {\n  const page = await ctx.newPage();\n} catch (e) {\n  if (/applying init scripts/.test(String(e))) return; // browser/session dead; skip iteration\n  throw e;\n}","preventionTips":["Register init scripts on the context before creating pages","Keep init script sources plain, valid JS strings","Don't create pages while the context/browser is closing"],"tags":["cdp","browser","init-script","page-creation","lifecycle"],"backgroundTag":null,"analyzedSha":"93accf6570dcd306ca5e99cc44c393ee3797761b","analyzedAt":"2026-08-15T21:23:27.118Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}