Capture & display the error message on console

252 views Asked by At

enter image description here

How to get the text which is displayed as the error message in the screenshot attached ? I could not inspect it.

I tried using the below selenium java code but it failed:

String ale=driver.switchTo().alert().getText();
System.out.println(ale);

The error message displayed is

Exception in thread "main" org.openqa.selenium.NoAlertPresentException:no such alert

How can I fix it ?

1

There are 1 answers

0
Abhishek Dhoundiyal On

You can get the message and the state by using the JavascriptExecutor:

Note: You just need to provide the input WebElement for each input tag.

Code:

WebElement ele = driver.findElement(By.xpath("(//*[@type='email'])[2]"));
JavascriptExecutor js = (JavascriptExecutor) driver;
Boolean isValidInput = (Boolean)js.executeScript("return arguments[0].checkValidity();", ele);
System.out.println(isValidInput);
String validationMessage = (String)js.executeScript("return arguments[0].validationMessage;", ele);
System.out.println(validationMessage);

Screenshot:

enter image description here