JavascriptException
JavascriptException: Causes and Fixes
Fix Selenium JavascriptException (JavascriptError in JS, JavaScriptException in C#): null elements, syntax errors and missing libraries in executeScript.
| Java | org.openqa.selenium.JavascriptException |
|---|---|
| Python | selenium.common.exceptions.JavascriptException |
| JavaScript | JavascriptError |
| C# | OpenQA.Selenium.JavaScriptException |
What the error means
Code you ran with executeScript or executeAsyncScript threw an exception inside the browser. The driver catches it and returns it to your test as a “javascript error”, with the browser’s own error message attached.
Read the part after javascript error:. It is a normal browser error (TypeError, ReferenceError, SyntaxError) and you debug it exactly as you would in the DevTools console. In fact, pasting the script into the console on the same page is usually the fastest diagnosis.
What it looks like
// Javaorg.openqa.selenium.JavascriptException: javascript error: Cannot read properties of null (reading 'click') (Session info: chrome=131.0.6778.86) at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:...)# Pythonselenium.common.exceptions.JavascriptException: Message: javascript error: $ is not defined (Session info: chrome=131.0.6778.86)// JavaScript (selenium-webdriver)JavascriptError: javascript error: Unexpected token ')' (Session info: chrome=131.0.6778.86)// C#OpenQA.Selenium.JavaScriptException : javascript error: arguments[0].scrollIntoView is not a functionFirefox includes the error type: TypeError: document.querySelector(...) is null.
Common causes
- A DOM query returned null.
document.querySelector('#save').click()when#savedoes not exist yet. - Wrong argument passing. Building element references into the script string, using the wrong
argumentsindex, or passing something that does not serialise to a DOM element. - A page library is not loaded.
$,angular, or an app global is used before the page script that defines it has run, or the page simply does not use it. - Syntax errors in the script string. Unescaped quotes, a missing bracket, or modern syntax inside an old embedded browser.
- Async scripts handled incorrectly. Using
awaitat the top level ofexecuteScript, or rejecting a promise inexecuteAsyncScriptinstead of calling the callback. - The page navigated while the script ran, destroying the execution context.
How to fix it
A DOM query returned null
Find the element with WebDriver (with a wait if needed) and pass it in as an argument. You get WebDriver’s clear errors and waits instead of a TypeError.
WebElement save = new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.presenceOfElementLocated(By.id("save")));((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView({block: 'center'});", save);save = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "save")))driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", save)const save = await driver.wait(until.elementLocated(By.id('save')), 10000);await driver.executeScript("arguments[0].scrollIntoView({block: 'center'});", save);IWebElement save = new WebDriverWait(driver, TimeSpan.FromSeconds(10)) .Until(d => d.FindElement(By.Id("save")));((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView({block: 'center'});", save);If you must query in the script, guard against null and return a value your test can check: const el = document.querySelector('#save'); if (!el) return false; el.click(); return true;.
Wrong argument passing
Arguments are available as arguments[0], arguments[1], and so on, in the order you pass them. Elements arrive as live DOM nodes; strings, numbers, booleans, lists and maps arrive as their JavaScript equivalents. Never concatenate values into the script text; pass them as arguments, which also removes quoting problems.
WebElement input = driver.findElement(By.id("search"));((JavascriptExecutor) driver).executeScript( "arguments[0].setAttribute(arguments[1], arguments[2]);", input, "data-qa", "O'Brien");search = driver.find_element(By.ID, "search")driver.execute_script( "arguments[0].setAttribute(arguments[1], arguments[2]);", search, "data-qa", "O'Brien")const input = await driver.findElement(By.id('search'));await driver.executeScript('arguments[0].setAttribute(arguments[1], arguments[2]);', input, 'data-qa', "O'Brien");IWebElement input = driver.FindElement(By.Id("search"));((IJavaScriptExecutor)driver).ExecuteScript( "arguments[0].setAttribute(arguments[1], arguments[2]);", input, "data-qa", "O'Brien");A page library is not loaded
Wait until the global exists before using it. This is a good use of a custom wait.
JavascriptExecutor js = (JavascriptExecutor) driver;new WebDriverWait(driver, Duration.ofSeconds(10)).until( d -> (Boolean) js.executeScript("return typeof window.appStore !== 'undefined';"));Object cartCount = js.executeScript("return window.appStore.getState().cart.items.length;");WebDriverWait(driver, 10).until( lambda d: d.execute_script("return typeof window.appStore !== 'undefined';"))cart_count = driver.execute_script("return window.appStore.getState().cart.items.length;")await driver.wait(() => driver.executeScript("return typeof window.appStore !== 'undefined';"), 10000);const cartCount = await driver.executeScript('return window.appStore.getState().cart.items.length;');var js = (IJavaScriptExecutor)driver;new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until( d => (bool)js.ExecuteScript("return typeof window.appStore !== 'undefined';"));object cartCount = js.ExecuteScript("return window.appStore.getState().cart.items.length;");Also check that the code is running in the right frame. A global defined in the top document does not exist inside an iframe, and vice versa.
Syntax errors in the script string
Keep scripts short. For anything longer than a line or two, store the script in a resource file and load it, so your editor can lint it. Remember that executeScript runs your code as the body of a function: use return to send a value back, and do not wrap it in another function you never call.
Async scripts handled incorrectly
executeScript already waits for a returned promise to settle in current drivers, so the simplest approach is to return a promise. With executeAsyncScript, the last argument is a callback that you must call, including on error paths; otherwise you get a script timeout instead.
Object status = ((JavascriptExecutor) driver).executeScript( "return fetch('/api/health').then(r => r.status);");status = driver.execute_script("return fetch('/api/health').then(r => r.status);")const status = await driver.executeScript("return fetch('/api/health').then(r => r.status);");object status = ((IJavaScriptExecutor)driver).ExecuteScript( "return fetch('/api/health').then(r => r.status);");If the promise rejects, you get a JavascriptException carrying the rejection message, which is usually what you want.
The page navigated while the script ran
Do not run scripts that trigger navigation and also return data. Trigger the navigation, then wait for the new page with a normal explicit wait, then run any follow-up script.
How to prevent it
- Use the WebDriver API first;
executeScriptis for things WebDriver cannot do, not a shortcut around waits. - Pass all values as arguments; never build script text from data.
- Test non-trivial scripts in the DevTools console on the real page.
- Collect browser console logs on failure (via BiDi log events) so errors from the page and your scripts are visible.
- Read the JavaScript executor lesson for the full set of safe patterns.
Related errors
- TimeoutException: an async script that never called its callback.
- StaleElementReferenceException: passing an element that was replaced before the script ran.
- UnhandledAlertException: a dialog blocked script execution.
- InvalidSelectorException: the locator, not your script, is malformed.
Go deeper
- JavaScript Executor Execute JavaScript directly in the browser for advanced interactions and DOM manipulation.
- Custom Wait Conditions Write your own expected conditions with lambdas and classes, wait for attribute and text changes, element counts, JavaScript state, network idleness via BiDi, and compose conditions cleanly.
- Browser and Driver Logs Turn on the logs that explain failures: browser console output via BiDi, chromedriver and geckodriver logs, Selenium's own client logging, network failures, and how to collect them per test.