Open In App

Understanding execute async script in Selenium Using java

Last Updated : 08 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Understanding executeAsyncScript in Selenium Using Java is crucial for handling asynchronous JavaScript operations during test automation. The executeAsyncScript method allows Selenium to wait for certain operations, like AJAX calls or timeouts, to complete before proceeding.

This is particularly useful when automating dynamic web applications that load content in the background, making it a valuable tool in your Selenium test suite.

Example to execute async script in Selenium Using Java

Here is an example to execute async script in Selenium Using Java

Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;

public class ExecuteAsyncScriptMethod {
    public static void main(String[] args) {
        // Set the path for the ChromeDriver executable
        System.setProperty("webdriver.chrome.driver", "path of Chromedriver.exe//chromedriver.exe");//change the path as per need

        // Initialize ChromeDriver
        WebDriver driver = new ChromeDriver();

        // Open the GeeksforGeeks website
        driver.get("https://www.geeksforgeeks.org");

        // Get current system time
        long startTime = System.currentTimeMillis();

        // Create an instance of JavascriptExecutor
        JavascriptExecutor js = (JavascriptExecutor) driver;

        // Execute async script to set timeout
        js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 800);");

        // Print elapsed time
        System.out.println("Time Elapsed is: " + (System.currentTimeMillis() - startTime) + " milliseconds");

        // Close the browser
        driver.quit();
    }
}

Output

output
Output

Conclusion

In conclusion, mastering executeAsyncScript in Selenium Using Java enables efficient handling of asynchronous operations, ensuring that your tests accurately capture real-time changes on web pages. By incorporating this method, you can improve the stability and reliability of your automated tests, especially when working with modern, dynamic websites.


Next Article
Article Tags :

Similar Reads