grafana/k6 · error
getting element handle for selector %q: %w
Error message
getting element handle for selector %q: %w
What it means
queryAll type-asserted the evaluation result to JSHandleAPI and failed, wrapping the sentinel ErrJSHandleInvalid ('JS handle is invalid', errors.go:23) with the selector (element_handle.go:1281). The protocol result was not a materialized object handle — an internal invariant break or an invalid handle from a destroyed context, not a selector problem.
Source
Thrown at internal/js/modules/k6/browser/common/element_handle.go:1281
return nil, fmt.Errorf("parsing selector %q: %w", selector, err)
}
result, err := eval(
h.ctx,
evalOptions{forceCallable: true, returnByValue: false},
js.QueryAll,
parsedSelector,
)
if err != nil {
return nil, fmt.Errorf("querying all selectors %q: %w", selector, err)
}
if result == nil {
// it is ok to return a nil slice because it means we didn't find any elements.
return nil, nil
}
handles, ok := result.(JSHandleAPI)
if !ok {
return nil, fmt.Errorf("getting element handle for selector %q: %w", selector, ErrJSHandleInvalid)
}
defer func() {
if err := handles.Dispose(); err != nil {
err = fmt.Errorf("disposing element handles: %w", err)
rerr = errors.Join(err, rerr)
}
}()
props, err := handles.GetProperties()
if err != nil {
// GetProperties has a rich error already, so we don't need to wrap it.
return nil, err //nolint:wrapcheck
}
type indexedElem struct {
index int
elem *ElementHandle
}View on GitHub (pinned to 93accf6570)
Solutions
- Upgrade k6 to the latest version
- If reproducible, capture the script + versions and file a k6 issue
- Work around using page.$$ on the page or frame instead of element.$$
- Retry once — a context-teardown race produces this only transiently
Defensive patterns
Strategy: try-catch
Try / catch
try { return await el.$$(sel); }
catch (e) { if (/JS handle is invalid/.test(e.message)) { return await page.$$(sel); /* page-level fallback */ } throw e; } Prevention
- Keep k6/chromium versions in sync
- Use page.$$ as a fallback path when element.$$ hits the invariant
- Report reproducible occurrences upstream
When it happens
Trigger: A chromium/CDP version returning an unexpected result shape for the injected script; evaluation resolving after the context was destroyed so the handle is invalid; k6 browser-module bug.
Common situations: Rare and typically version-correlated (after a chromium bump) or load-correlated (context teardown races).
Related errors
- querying selector %q, wrong type %T
- can't fetch the page for unknown reason
- adding k6 object to new browser context: %w
- parsing element index %q for selector %q: %w
- unpacking selected options: %w
AI-assisted analysis of grafana/k6@93accf6570 (2026-08-15).
Data as JSON: /api/errors/06831ab24d721f44.
Report an issue: GitHub.