AjaxElementLocator and AjaxElementLocatorFactory

Selenium comes with AjaxElementLocator and AjaxElementLocatorFactory intending to make our life easier to automate ajax heavy applications. But my experience with it: it is of not much help. Certainly you will get a lot of StaleElementReferenceException if you solely rely on them. How so? Let’s take a closer look at these 2 classes.

AjaxElementLocator per Selenium Java Doc, is

An element locator that will wait for the specified number of seconds for an element to appear, rather than failing instantly if it’s not present. This works by polling the UI on a regular basis. The element returned will be present on the DOM, but may not actually be visible: override isElementUsable(WebElement) if this is important to you. Because this class polls the interface on a regular basis, it is strongly recommended that users avoid locating elements by XPath.

And AjaxElementLocatorFactory is a way to create page using lazy loading and applying this a timeout for locating to all elements on this page:

//Wait for up to 10 seconds if the element is not immediately found on your page
PageFactory.initElements(new AjaxElementLocatorFactory(driver, 10); , YourPage.class);

This is more like adding implicitWait for the page. this will not address StaleElementReferenceException caused by ajax: StaleElementReferenceException will not manifest until user interact with the element, in another word, you won’t know a reference is stale until you try to DO SOMETHING with it, like clicking.

In summary: Don’t rely on AjaxElementLocator, Instead, handle ajax elements this way.

Leave a Reply

Your email address will not be published. Required fields are marked *