Tuesday, February 16, 2016

How to handle Java Scripts Alerts in Webdriver

In general JavaScript popups are generated by web application and can be handled by WebDriver.
Webdriver offers the ability to handle with javascript alerts using Alerts API
// Get a handle to the open alert, prompt or confirmation
 Alert alert = driver.switchTo().alert();
//Will Click on OK button.
alert.accept(); 
alert.authenticateUsing(Credentials credentials)


// Will click on Cancel button.
alert.dismiss()
//will get the text which is present on the alert.
alert.getText(); 
//Will pass the text to the prompt popup

alert.sendkeys();
Alert is an interface. There below are the methods that are used
 Lets take an example 
1. Open google chrome 
2. Navigate to site : http://admin-demo.nopcommerce.com/login
3. Go to Catalog->Product tags
4. And delete the product

SCRIPT :
package com.test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class JSscripts {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","yourpath//chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://admin-demo.nopcommerce.com/login");
Thread.sleep(6000);
driver.findElement(By.xpath(".//*[@id='Email']")).sendKeys("admin@yourstore.com");
driver.findElement(By.xpath(".//*[@id='Password']")).sendKeys("admin");
driver.findElement(By.xpath("html/body/div[1]/div/div/div/div/div[2]/div[1]/div/form/div[3]/input")).click();
Thread.sleep(6000);
//driver.findElement(By.xpath("//li[2]/a/span")).click();
driver.findElement(By.linkText("Catalog")).click();
// /html/body/div[3]/div[2]/div/ul/li[2]/ul/li[1]/a/span
Thread.sleep(3000);
driver.findElement(By.linkText("Product tags")).click();
Thread.sleep(4000);
driver.findElement(By.xpath("//*[@id='product-tags-grid']/table/tbody/tr[1]/td[4]/a")).click();
Thread.sleep(3000);
Alert a = driver.switchTo().alert();
// to click on cancel button
// a.dismiss();
// to click on ok button
a.accept();
}
}
view raw jsscript.java hosted with ❤ by GitHub