Home > Software engineering >  How to click on a Web Element using JS Executor and wait until script executed?
How to click on a Web Element using JS Executor and wait until script executed?

Time:05-11

I have XPath of the button. I need to click on this button using JSExecutor and wait until script is executed. I suppose it can be done with ExpectedCondition.javaScriptThrowsNoExceptions(String script). But I don't know how implement it with XPath. I am using Java.

CodePudding user response:

In my point of view, you must know what the button does

If there's a change in UI

ExpectedConditions.visibilityOf(WebElement element) will be better solution

In case javascript returns true/false, driver will wait the return from script execute

 new WebDriverWait(driver, Duration.ofSeconds(20)).until(new ExpectedCondition<Boolean>(){
    public Boolean apply(WebDriver driver) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        return (Boolean) js.executeScript("console.log('wait');return 1 1==2");
    }
});

CodePudding user response:

Forming your xpath :

//tagname[@attributekey='attribute value']

after that pass it driver with wait

public By operation_first_Asset = By.xpath("//a[@analytics-category='Asset Operations']");

WebDriver driver = new ChromeDriver();


WebDriverWait wait = new WebDriverWait(driver, Duration.ofMinutes(2));


 /*
 * @param by, count, operation
 * wait based on the list of elements
 */
public void waitForElementToBe(By by, String action) {
    try {
        if (action.equals("click")) {
            wait.until(ExpectedConditions.elementToBeClickable(by));
        } else if (action.equals("visible")) {
            wait.until(ExpectedConditions.visibilityOfElementLocated(by));
        } else if (action.equals("invisible")) {
            wait.until(ExpectedConditions.invisibilityOfElementLocated(by));
        } else if (action.equals("presence")) {
            wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(by));
        }
    } catch (Exception err) {
        err.printStackTrace();
        throw err;
    }
}
  • Related