{"record":{"id":"e18f163ac632c3d7","repo":"grafana/k6","slug":"creating-a-new-s-w","errorCode":null,"errorMessage":"creating a new %s: %w","messagePattern":"creating a new (.+?): %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/js/modules/k6/browser/common/browser.go","lineNumber":330,"sourceCode":"\t)\n\t// Opener is nil for the initial page.\n\tif isPage {\n\t\tb.pagesMu.RLock()\n\t\tif t, ok := b.pages[targetPage.OpenerID]; ok {\n\t\t\topener = t\n\t\t}\n\t\tb.pagesMu.RUnlock()\n\t}\n\tp, err := NewPage(b.vuCtx, session, browserCtx, targetPage.TargetID, opener, isPage, b.logger)\n\tif err != nil && b.isPageAttachmentErrorIgnorable(ev, session, err) {\n\t\tif b.closing.Load() {\n\t\t\tb.logger.Debugf(\"Browser:onAttachedToTarget\", \"new page failed; browser is closing: sid:%v\", ev.SessionID)\n\t\t\tdetachSession(b.browserCtx, session)\n\t\t}\n\t\treturn nil // Ignore this page.\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating a new %s: %w\", targetPage.Type, err)\n\t}\n\n\t// This prevents a race where Close() sets closing and snapshots\n\t// pages, but a new page is inserted outside that snapshot.\n\tif err := b.attachNewPage(p, ev); err != nil {\n\t\tif !errors.Is(err, errBrowserClosing) {\n\t\t\treturn fmt.Errorf(\"attaching new page: %w\", err)\n\t\t}\n\n\t\tb.logger.Debugf(\n\t\t\t\"Browser:onAttachedToTarget\",\n\t\t\t\"rejected page attachment; browser is closing: sid:%v tid:%v\",\n\t\t\tev.SessionID, ev.TargetInfo.TargetID,\n\t\t)\n\t\tif closeErr := p.Close(); closeErr != nil {\n\t\t\tb.logger.Debugf(\n\t\t\t\t\"Browser:onAttachedToTarget\",\n\t\t\t\t\"closing rejected page: %v\", closeErr,","sourceCodeStart":312,"sourceCodeEnd":348,"githubUrl":"https://github.com/grafana/k6/blob/93accf6570dcd306ca5e99cc44c393ee3797761b/internal/js/modules/k6/browser/common/browser.go#L312-L348","documentation":"Returned by Browser.onAttachedToTarget when NewPage fails for an incoming target (the '%s' is the target type, e.g. 'page' or 'background_page') and the error is not an ignorable page-attachment failure (browser closing races are ignored separately). This error is delivered asynchronously: initEvents' event loop handles it via k6ext.Panicf('browser is attaching to target: ...'), which aborts the VU iteration. It usually means a page/iframe target appeared while the CDP session or context was in a bad state.","triggerScenarios":"A new page or popup attaching while the connection is degraded or the session was already detached; NewPage's internal setup CDP calls failing (e.g. target crashed concurrently); pages created by the site under test (window.open, popups, OAuth flows) arriving during teardown races that are not classified as ignorable; Chrome extensions spawning background pages with malformed targets.","commonSituations":"Tests clicking links that trigger popups/OAuth redirects while k6 is also navigating/closing; remote Chrome under heavy load dropping sessions; site under test spawning many targets; usually surfaces as an iteration abort with 'browser is attaching to target: creating a new page: ...'.","solutions":["Read the full chain ('browser is attaching to target: creating a new page: <cause>') to see whether it is a session/closed error or a CDP protocol error","Avoid triggering unhandled popups: block them via launch args or handle window.open targets explicitly in the test flow","If it happens under load, increase K6_BROWSER_TIMEOUT and reduce concurrent browser activity against the same Chrome instance","Ensure you are not closing pages/contexts concurrently while new targets appear (serialize close and open operations in the script)","Update k6 — attachment-error classification (isPageAttachmentErrorIgnorable) has been improved over releases; report reproductions to k6 issues"],"exampleFix":"// before\npage.click('#open-popup');  // popup target arrives while script closes context\nbrowser.close();\n\n// after\nconst popupPromise = page.waitForEvent('popup');\npage.click('#open-popup');\nconst popup = await popupPromise;\npopup.close();\nbrowser.close();","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"// The error surfaces as an iteration panic ('browser is attaching to target: creating a new page: ...').\n// Guard the flows that spawn targets:\ntry {\n  const popupPromise = page.waitForEvent('popup');\n  await page.click('#open-popup');\n  const popup = await popupPromise;\n  await popup.close();\n} catch (e) {\n  if (String(e.message).includes('creating a new')) {\n    console.error('A target attached while the session/context was unstable; serialize opens/closes:', e.message);\n  }\n  throw e;\n}","preventionTips":["Handle popups and window.open targets explicitly with waitForEvent('popup') instead of letting them arrive unmanaged","Serialize page/context open and close operations; never close while targets may attach","Upgrade k6 regularly — target-attachment error handling keeps improving","Keep remote Chrome load within limits so sessions do not drop mid-attach"],"tags":["cdp","pages","event-handling","race-condition","async"],"backgroundTag":null,"analyzedSha":"93accf6570dcd306ca5e99cc44c393ee3797761b","analyzedAt":"2026-08-15T21:23:27.118Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}