Sapna
Sapna

Reputation: 59

How to read alert message using Firefox Driver?

I need to read alert & confirmation messages displayed in pop ups using java and print it on the console. On export of the selenium recording from the IDE as a Junit4 (WebDriver) java file, my code is:

private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();

@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
}

Now when I tried to use getAlert or getConfirmation functions as shown:

@Test
public void testSample() throws Exception {
Alert alert = driver.switchTo().alert();
message = alert.getText();
System.out.println("message is "+message);
}

I get the following error:

java.lang.NullPointerException
at com.example.tests.Sample.testSample(Sample.java:40)
at com.example.tests.Sample.main(Sample.java:149)
Exception: null

How do I handle this? Also is there any other way of reading the pop up messages?

Upvotes: 3

Views: 3748

Answers (1)

Hari Reddy
Hari Reddy

Reputation: 3858

In the testSample() method when you navigate to any page by using -

driver.get("URL");

After that can you explain how the alert message comes up in the 1st place.

Are you sure that the pop up message which appears is a javascript alert or any window which is opening up.

If it is a an alert message then you can access it by using -

driver.switchTo().alert();

But if the pop up is another window then you will have to use -

driver.switchTo().window("windowName");

You can get more information about this from here.

Upvotes: 5

Related Questions