grafana/k6 · error

document element handle is nil

Error message

document element handle is nil

What it means

The evaluate of 'document' returned no error but also no result: the remote object came back nil (the code logs 'remoteObject is nil' at Debug level in ExecutionContext.eval). That happens while a context is being torn down — Chrome accepts the evaluation but the object never materializes. It is a nil-check guard in newDocumentHandle signaling the same navigation/teardown race as its siblings, not a script error.

Source

Thrown at internal/js/modules/k6/browser/common/frame.go:292

	return f.documentHandle, f.documentHandle != nil
}

func (f *Frame) newDocumentHandle() (*ElementHandle, error) {
	result, err := f.evaluate(
		f.ctx,
		mainWorld,
		evalOptions{
			forceCallable: false,
			returnByValue: false,
		},
		"document",
	)
	if err != nil {
		return nil, fmt.Errorf("getting document element handle: %w", err)
	}
	if result == nil {
		return nil, fmt.Errorf("document element handle is nil")
	}
	dh, ok := result.(*ElementHandle)
	if !ok {
		return nil, fmt.Errorf("unexpected document handle type: %T", result)
	}

	return dh, nil
}

func (f *Frame) hasContext(world executionWorld) bool {
	f.executionContextMu.RLock()
	defer f.executionContextMu.RUnlock()

	return f.executionContexts[world] != nil
}

func (f *Frame) hasLifecycleEventFired(event LifecycleEvent) bool {
	f.lifecycleEventsMu.RLock()

View on GitHub (pinned to 93accf6570)

Solutions

  1. Retry the query after waiting for load state
  2. Synchronize navigations with waitForNavigation before querying
  3. Avoid querying during page teardown; sequence actions before close()
Defensive patterns

Strategy: retry

Try / catch

try {
  el = await page.waitForSelector('#x');
} catch (e) {
  if (/document element handle is nil/.test(e.message)) {
    await page.waitForLoadState();
    el = await page.waitForSelector('#x');
  } else throw e;
}

Prevention

When it happens

Trigger: Evaluating 'document' exactly as the context is destroyed by navigation; frame detach between context acquisition and evaluation; page closing mid-query.

Common situations: Fast SPA transitions; queries fired at the tail end of an iteration while the browser cleans up; flaky timing on CI machines.

Related errors


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