grafana/k6 · error
getting document element handle: %w
Error message
getting document element handle: %w
What it means
newDocumentHandle evaluates the expression 'document' in the frame's main world with returnByValue=false; any evaluation failure is wrapped here. It fires when the execution context k6 was about to use no longer exists — the classic navigation race — or when the frame's target is detached/closed. It is the inner error that 751 wraps.
Source
Thrown at internal/js/modules/k6/browser/common/frame.go:289
// see: nullContext().
f.executionContextMu.RLock()
defer f.executionContextMu.RUnlock()
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
}View on GitHub (pinned to 93accf6570)
Solutions
- Wait for load state after navigations before any query
- Retry the query — the recreated context will serve it
- Verify the frame is still attached (page.frames()) before using a stored reference
- Avoid document-dependent calls during teardown
Defensive patterns
Strategy: retry
Try / catch
try {
el = await frame.waitForSelector('#x');
} catch (e) {
if (/document element handle|Execution context was destroyed/.test(e.message)) {
await page.waitForLoadState();
el = await frame.waitForSelector('#x');
} else throw e;
} Prevention
- Wait for load state after navigations before any query
- Verify a stored frame is still in page.frames() before using it
- Avoid document-dependent calls during page teardown
When it happens
Trigger: Evaluating 'document' while the context is destroyed by a navigation; the frame's session closing (page/target shutdown); the frame detached between the cached-handle check and the evaluation.
Common situations: Element queries immediately after goto or form submits; SPA route changes between actions; iterating over frames while the page unloads them.
Related errors
- getting document: %w
- setting content: %w
- getting frame title: %w
- missing required argument 'url'
- getting injected script: %w
AI-assisted analysis of grafana/k6@93accf6570 (2026-08-15).
Data as JSON: /api/errors/2bc44ffa37df4bec.
Report an issue: GitHub.