{"record":{"id":"e37bb06bcb64ebe1","repo":"grafana/k6","slug":"getting-injected-script-w","errorCode":null,"errorMessage":"getting injected script: %w","messagePattern":"getting injected script: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"internal/js/modules/k6/browser/common/element_handle.go","lineNumber":1596,"sourceCode":"// WaitForSelector waits for the selector to appear in the DOM.\nfunc (h *ElementHandle) WaitForSelector(selector string, opts *FrameWaitForSelectorOptions) (*ElementHandle, error) {\n\thandle, err := h.waitForSelector(h.ctx, selector, opts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"waiting for selector %q: %w\", selector, err)\n\t}\n\n\treturn handle, nil\n}\n\n// evalWithScript evaluates the given js code in the scope of this ElementHandle and returns the result.\n// The js code can call helper functions from injected_script.js.\nfunc (h *ElementHandle) evalWithScript(\n\tctx context.Context,\n\topts evalOptions, js string, args ...any,\n) (any, error) {\n\tscript, err := h.execCtx.getInjectedScript(h.ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting injected script: %w\", err)\n\t}\n\treturn h.eval(ctx, opts, js, append([]any{script}, args...)...)\n}\n\n// eval evaluates the given js code in the scope of this ElementHandle and returns the result.\nfunc (h *ElementHandle) eval(\n\tctx context.Context,\n\topts evalOptions, js string, args ...any,\n) (any, error) {\n\t// passing `h` makes it evaluate js code in the element handle's scope.\n\treturn h.execCtx.eval(ctx, opts, js, append([]any{h}, args...)...)\n}\n\nfunc (h *ElementHandle) newAction(\n\tstates []string, fn elementHandleActionFunc, force bool, retry bool, noWaitAfter bool, timeout time.Duration,\n) func(apiCtx context.Context, resultCh chan any, errCh chan error) {\n\t// All or a subset of the following actionability checks are made before performing the actual action:\n\t// 1. Attached to DOM","sourceCodeStart":1578,"sourceCodeEnd":1614,"githubUrl":"https://github.com/grafana/k6/blob/93accf6570dcd306ca5e99cc44c393ee3797761b/internal/js/modules/k6/browser/common/element_handle.go#L1578-L1614","documentation":"Failure inside evalWithScript, the helper every injected-script-based element method uses (click/fill/selectText/checks/etc.): getInjectedScript could not produce the JSHandle to the InjectedScript instance. The inner error is an evaluation failure in the frame's execution context (context destroyed by navigation, target closed) or the evaluated handle being nil / not a JSHandle (ErrJSHandleInvalid).","triggerScenarios":"Calling an element action while the frame is navigating (Runtime.evaluate fails with context destroyed); acting on a handle after page.close()/context.close(); the browser tab crashing; executing against an about:blank frame that has just been swapped.","commonSituations":"Acting on handles immediately after a click that navigates, without waiting for the new document; parallel VUs sharing a browser context that gets closed by one iteration; OOM-killed chromium in constrained containers.","solutions":["After any action that can navigate, wait for load before reusing handles: page.waitForLoadState() or page.waitForNavigation()","Always re-query element handles after navigation instead of reusing pre-navigation handles","Ensure the page/context is still open before acting (do not close early in the iteration)","Give chromium enough memory/CPU in the environment if targets are crashing"],"exampleFix":"// before\npage.$('#submit').click();\npage.$('.result').textContent(); // context destroyed: getting injected script\n\n// after\npage.$('#submit').click();\npage.waitForLoadState('load');\npage.waitForSelector('.result', { state: 'attached' }).textContent();","handlingStrategy":"validation","validationCode":"// never reuse pre-navigation handles: settle the page first\npage.waitForLoadState('load');\nconst el = page.waitForSelector('#target', { state: 'attached' });\nel.click();","typeGuard":null,"tryCatchPattern":"try {\n  el.click();\n} catch (e) {\n  if (String(e).includes('getting injected script')) {\n    // context was destroyed: re-query after load and retry once\n    page.waitForLoadState('load');\n    page.waitForSelector('#target', { state: 'attached' }).click();\n  } else {\n    throw e;\n  }\n}","preventionTips":["Wait for load state after navigations before any element action","Re-query handles after every navigation","Do not close the page/context while actions are still in flight"],"tags":["browser","execution-context","navigation","race-condition","injected-script"],"backgroundTag":null,"analyzedSha":"93accf6570dcd306ca5e99cc44c393ee3797761b","analyzedAt":"2026-08-15T21:23:27.118Z","schemaVersion":2},"datasetVersion":"2026-08-16T03:17:38.424Z"}