grafana/k6 · error

adding init script to browser context

Error message

adding init script to browser context: %w

What it means

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.

Solutions

  1. Call addInitScript immediately after browser.newContext(), before any newPage() call, so the per-page loop iterates over nothing
  2. If pages exist, make sure they are alive and not being closed concurrently (await your page.close() calls) before adding the script
  3. Use a fresh browserContext per iteration/VU so no half-dead pages accumulate in the context
  4. Check the wrapped error: if the browser process died, restart the browser/browser option rather than retrying the same context
  5. Upgrade k6 — older builds had races between page teardown and context-level operations

Example fix

// before
const ctx = browser.newContext();
const page = ctx.newPage();
// ... later, page may be closing/crashed
ctx.addInitScript('window.flag = true'); // can fail on existing pages

// after
const ctx = browser.newContext();
ctx.addInitScript('window.flag = true'); // no pages yet, nothing to replay onto
const page = ctx.newPage();
Defensive patterns

Strategy: try-catch

Validate before calling

// register init scripts before any page exists, so the per-page replay loop is empty
const ctx = browser.newContext();
ctx.addInitScript('window.flag = true'); // no pages yet -> cannot fail per-page
const page = ctx.newPage();

Try / catch

try {
  ctx.addInitScript(script);
} catch (e) {
  if (String(e.message).includes('adding init script')) {
    // existing page session is dead: recreate context (script is re-registered) and new pages
    console.warn(`init script replay failed: ${e.message}`);
  } else {
    throw e;
  }
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of grafana/k6@01ffac6f24 (2026-08-18). Data as JSON: /api/errors/f50c2c70cba8abb8. Report an issue: GitHub.

Appendix: source

Thrown at internal/js/modules/k6/browser/common/browser_context.go:171

	if err := b.AddInitScript(js.WebVitalInitScript); err != nil {
		return nil, fmt.Errorf("adding web vital init script to new browser context: %w", err)
	}
	if err := b.setDownloadsPath(opts.DownloadsPath); err != nil {
		return nil, fmt.Errorf("setting downloads path: %w", err)
	}

	return &b, nil
}

// AddInitScript adds a script that will be initialized on all new pages.
func (b *BrowserContext) AddInitScript(script string) error {
	b.logger.Debugf("BrowserContext:AddInitScript", "bctxid:%v", b.id)

	b.evaluateOnNewDocumentSources = append(b.evaluateOnNewDocumentSources, script)

	for _, p := range b.browser.getPages() {
		if err := p.evaluateOnNewDocument(script); err != nil {
			return fmt.Errorf("adding init script to browser context: %w", err)
		}
	}

	return nil
}

func (b *BrowserContext) applyAllInitScripts(p *Page) error {
	for _, source := range b.evaluateOnNewDocumentSources {
		if err := p.evaluateOnNewDocument(source); err != nil {
			return fmt.Errorf("adding init script to browser context: %w", err)
		}
	}

	return nil
}

// Browser returns the browser instance that this browser context belongs to.
func (b *BrowserContext) Browser() *Browser {

View on GitHub (pinned to 01ffac6f24)