{"record":{"id":"d9a990dd9eb4e5db","repo":"karatelabs/karate","slug":"javascript-failed-message","errorCode":null,"errorMessage":"javascript failed: ${message}","messagePattern":"javascript failed: (.+?)","errorType":"exception","errorClass":"DriverException","httpStatus":null,"severity":"error","filePath":"karate-core/src/main/java/io/karatelabs/driver/w3c/W3cDriver.java","lineNumber":206,"sourceCode":"        // - Starts with a bare expression (no var/let/const/if/for) → prefix \"return\"\n        // - Statement blocks (var/let/const/if/for/try) → execute as-is (no return value)\n        // Inject __kjs runtime if the script references it (wildcard locators, shadow DOM)\n        if (js.contains(\"__kjs\")) {\n            ensureKjsRuntime();\n        }\n        String expression = prefixReturnIfNeeded(js);\n        Object result;\n        try {\n            result = session.executeScript(expression);\n        } catch (Exception e) {\n            // v1 pattern: single retry on JS error — handles transient page-load timing issues\n            logger.warn(\"javascript failed, will retry once: {}\", e.getMessage());\n            sleep(options.getRetryInterval());\n            try {\n                result = session.executeScript(expression);\n            } catch (Exception e2) {\n                logger.error(\"javascript failed twice: {}\", e2.getMessage());\n                throw new DriverException(\"javascript failed: \" + e2.getMessage(), e2);\n            }\n        }\n        return wrapElementReferences(result);\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    private Object wrapElementReferences(Object result) {\n        if (W3cSession.isElementReference(result)) {\n            String elementId = W3cSession.elementIdFrom(result);\n            return new W3cElement(this, \"(eval result)\", true, elementId, session);\n        }\n        if (result instanceof List) {\n            List<Object> list = (List<Object>) result;\n            boolean hasElements = list.stream().anyMatch(W3cSession::isElementReference);\n            if (hasElements) {\n                List<Object> wrapped = new ArrayList<>();\n                for (Object item : list) {\n                    if (W3cSession.isElementReference(item)) {","sourceCodeStart":188,"sourceCodeEnd":224,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-core/src/main/java/io/karatelabs/driver/w3c/W3cDriver.java#L188-L224","documentation":"W3cDriver.eval executes JavaScript in the page via the WebDriver executeScript endpoint. It retries once on failure (logging 'javascript failed, will retry once'); if the retry also throws, it wraps the error in DriverException 'javascript failed: <message>'. All element operations (click, input, clear, focus, scroll) go through this path, so any of them can surface this error.","triggerScenarios":"executeScript throws twice in a row — e.g. the page navigated or context was destroyed mid-script, the injected expression is invalid JS, or the WebDriver session is stale/dead.","commonSituations":"Clicking or typing during a page navigation; SPA replacing DOM nodes under the script; session invalidated after browser crash or manual close; a selector/JS snippet with a syntax error; alert dialog blocking script execution.","solutions":["Read the nested message to see the actual WebDriver/JS error","Wait for page readiness (e.g. waitFor/navigation settling) before the element operation, or add retry logic in the test","Fix syntax errors in any custom JS passed to script()","If the session is stale, re-initialize the driver/browser","Handle unexpected dialogs (accept/dismiss) before scripting"],"exampleFix":"// before\nclick('#submit') immediately after navigation triggers\n// after\nwaitFor('#submit');\nclick('#submit');","handlingStrategy":"retry","validationCode":"// wait for page readiness before element ops\ndriver.waitFor(\"#submit\");","typeGuard":null,"tryCatchPattern":"try {\n    driver.click(selector);\n} catch (DriverException e) {\n    if (e.getMessage().startsWith(\"javascript failed:\")) {\n        driver.waitFor(selector); // settle page, retry once\n        driver.click(selector);\n    } else throw e;\n}","preventionTips":["Use waitFor/waitUntil before interacting with elements after navigation","Avoid custom JS eval strings without testing them in devtools","Handle or suppress dialogs before scripting","Recreate the driver after browser crashes instead of reusing a dead session"],"tags":["javascript","webdriver","eval","retry"],"backgroundTag":"api-error-response","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}