grafana/k6 · error

internal error while applying init scripts to page: %w

Error message

internal error while applying init scripts to page: %w

What it means

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.

Source

Thrown at internal/js/modules/k6/browser/common/page.go:363

	p.frameSessions[cdp.FrameID(tid)] = p.mainFrameSession
	p.frameSessionsMu.Unlock()
	p.Mouse = NewMouse(ctx, s, p.frameManager.MainFrame(), bctx.timeoutSettings, p.Keyboard)
	p.Touchscreen = NewTouchscreen(ctx, s, p.Keyboard)

	p.initEvents()

	action := target.SetAutoAttach(true, true).WithFlatten(true)
	if err := action.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil {
		return nil, fmt.Errorf("internal error while auto attaching to browser pages: %w", err)
	}

	add := runtime.AddBinding(webVitalBinding)
	if err := add.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil {
		return nil, fmt.Errorf("internal error while adding binding to page: %w", err)
	}

	if err := bctx.applyAllInitScripts(&p); err != nil {
		return nil, fmt.Errorf("internal error while applying init scripts to page: %w", err)
	}

	return &p, nil
}

func (p *Page) initEvents() {
	p.logger.Debugf("Page:initEvents",
		"sid:%v tid:%v", p.session.ID(), p.targetID)

	events := []string{
		cdproto.EventRuntimeConsoleAPICalled,
	}
	p.session.on(p.ctx, events, p.eventCh)

	go func() {
		p.logger.Debugf("Page:initEvents:go",
			"sid:%v tid:%v", p.session.ID(), p.targetID)
		defer func() {

View on GitHub (pinned to 93accf6570)

Solutions

  1. Look upstream for the root session failure in the logs and address it
  2. Keep addInitScript + newPage sequences at the start of the iteration, away from close()
  3. 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)
  4. If persistent, upgrade k6 / verify the chromium binary version

Example fix

// before
const ctx = browser.newContext();
await ctx.close();
ctx.addInitScript('window.foo = 1');
const page = await ctx.newPage(); // applying init scripts on dead context

// after
const ctx = browser.newContext();
ctx.addInitScript('window.foo = 1');
const page = await ctx.newPage(); // init scripts applied while alive
await page.goto('https://test.k6.io/');
Defensive patterns

Strategy: retry

Validate before calling

const ctx = browser.newContext();
ctx.addInitScript('window.marker = 1;'); // register before any page exists
const page = await ctx.newPage();

Try / catch

try {
  const page = await ctx.newPage();
} catch (e) {
  if (/applying init scripts/.test(String(e))) return; // browser/session dead; skip iteration
  throw e;
}

Prevention

When it happens

Trigger: browser.newPage() after ctx.addInitScript(...) while the browser connection is broken, the browser crashed, or the target is being destroyed concurrently (close racing creation).

Common situations: Init scripts that assume a live target but creation races teardown; long tests where the browser died earlier; heavy page churn at iteration end.

Related errors


AI-assisted analysis of grafana/k6@93accf6570 (2026-08-15). Data as JSON: /api/errors/220e439eb08f81f3. Report an issue: GitHub.