AjaxElementLocatorFactory in Selenium
AjaxElementLocatorFactory in Selenium
AjaxElementLocatorFactory
is a class in Selenium used with PageFactory to deal with Ajax-based dynamic web elements that may not be immediately present on the page when it’s loaded.
It is a lazy load concept in Page Factory pattern to identify WebElements only when they are used in any operation i.e. a timeOut for a WebElement can be assigned to the Object page class with the help of AjaxElementLocatorFactory. It helps avoid NoSuchElementException
by waiting for the elements to appear before trying to locate them.
🔧 Why use AjaxElementLocatorFactory?
When dealing with modern web applications, elements often load asynchronously via AJAX. If your script tries to access them before they are present in the DOM, it throws an error.AjaxElementLocatorFactory
provides a way to wait for a web element up to a defined timeout.
Code Example
/***
* Constructor
* @param driver an instance of WebDriver
*/
public int TimeoutValue = 30;
public SearchResultsPage(Webdriver driver) {
PageFactory.initElements(new AjaxElementLocatorFactory(driver, TimeoutValue), this);
}
The above code snippet will wait for maximum of 30 seconds until the elements specified by annotations is loaded. If the element is not found in the given time interval, it will throw NoSuchElementException exception.