Reputation: 435
I need to grab a text from the alert box shown below. This alert box appears hovering above the url bar. Below is an example of my framework assertion:
verifyDisplay("'"+ driver.switchTo().alert().getText() + "'", By.xpath("xpath").
I am not sure, how to grab xpath
, id
, name
of this alert box, since there is none.
Any help is greatly appreciated.
Upvotes: 5
Views: 40944
Reputation: 1
Qus) How can the message in the alert box be retrieved?
Ans) storeAlert() command can be used to retrieve the message from the alert pop-up and store it in a variable.
Upvotes: -1
Reputation: 11
Just import the "org.openqa.selenium.Alert" lib and use below code to get the text from dialog boxes.
Alert confirmation = driver.switchTo().alert();
String alerttext = confirmation.getText();
System.out.println(alerttext);
Upvotes: 1
Reputation: 540
We can do one thing here get the HTML source in string and then find the 'alert(' and then we can substring the message inside the alert box ex-
var htmlString = document.getElementsByTagName('html')[0].innerHTML;
if(htmlString.includes('alert(')){
var indexOfAlertBeginning = htmlstring.indexof('alert(');
var stringFromAlert = htmlstring.substr(indexOfAlertBeginning);
var indexOfAlertEnd = stringFromAlert.indexof(')');
var alertMessages = stringFromAlert(0,indexOfAlertEnd);
console.log(alertMessages);
}
Please Try this and tell me if this workable
Upvotes: 0
Reputation: 4683
There is a method in Alert interface which gives you the text of the alert box message. As below:
Alert alert = driver.switchTo().alert();
alert.getText();
Let me know if you need further help.
Upvotes: 16