Async script execution lets your test wait for a task in the browser to finish before moving on. This helps test things that take time, like loading data.
0
0
Async script execution in Selenium Java
Introduction
When you want to wait for a timer or delay in the web page before checking results.
When testing a page that loads data slowly and you need to wait for it.
When you want to run JavaScript that calls a callback after some work is done.
When you need to test animations or transitions that finish after some time.
Syntax
Selenium Java
Object result = ((JavascriptExecutor)driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1]; window.setTimeout(function(){ callback('done'); }, 1000);"
);The last argument in the script is always a callback function you must call to finish.
executeAsyncScript waits until the callback is called or timeout happens.
Examples
This waits 500ms then returns 'hello' to Java.
Selenium Java
Object result = ((JavascriptExecutor)driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1]; window.setTimeout(function(){ callback('hello'); }, 500);"
);This runs a fetch call and returns the data when ready.
Selenium Java
Object result = ((JavascriptExecutor)driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1]; fetch('https://api.example.com/data').then(response => response.json()).then(data => callback(data));"
);Sample Program
This test opens a page, runs an async script that waits 1 second, then returns 'Async Done'. The result is printed.
Selenium Java
import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class AsyncScriptExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://www.example.com"); JavascriptExecutor js = (JavascriptExecutor) driver; Object result = js.executeAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.setTimeout(function() { callback('Async Done'); }, 1000);" ); System.out.println("Result from async script: " + result); } finally { driver.quit(); } } }
OutputSuccess
Important Notes
Always call the callback in your async script to avoid timeout errors.
Timeout for async scripts can be set in Selenium to control max wait time.
Async scripts help test real user waits like loading or animations.
Summary
Async script execution waits for JavaScript tasks to finish before continuing.
Use executeAsyncScript with a callback to handle delayed or async browser actions.
This helps test dynamic web pages that load or change over time.