How to handle Javascript alerts? Example using dismiss() method

User can handle the javascript alerts using alert() method.  For example,  when you click the popup button, alert message may appear.  While automating, user may need to handle this situation to accept or dismiss the alert. 

Below code is an example to handle the popup alert of www.qafreaks.com


CODE:

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class HandlingAlerts {
public static void main(String[] args) throws InterruptedException
{
//
System.setProperty("webdriver.chrome.driver", "C://Selenium_Training//chromedriver.exe");
WebDriver driver=new ChromeDriver();

//Launching qafreaks website and click the try it button for popup alert
driver.get("http://www.qafreaks.com/p/example-for-javascript-to-handle-alerts.html");
driver.findElement(By.id("tryit")).click();
	
Thread.sleep(10000);	
    
//Handling alert to accept
//driver.switchTo().alert().accept();
    
Alert alert = driver.switchTo().alert();   
alert.dismiss();
}

No comments:

Post a Comment

Socialize It and Share the post with your friends
SOCIALIZE IT →
FOLLOW US →
SHARE IT →