Some times while using webdriver we have to face login popup handle. When we passing the url using webdriver.get or webdriver.navigate.to("URL") at this time browser asks for login credentials.
For handle this situation we have to do following things.
1. HTTP Basic Authentication with Selenium WebDriver
the authentication prompt is not available from the Selenium WebDriver. One of the way to handle this limitation is to pass user and password in the url like like below:
http://username:password@the-site.com
So just to make it more clear. The username is
username
password is password
and the rest is usual URL of your test web WebDriver driver = getDriver();
String URL = "http://" + username + ":" + password + "@" + "link";
driver.get(URL);
but sometimes it does not work for IE browserwe can use robot method
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FillAuthAlert {
private static final String MY_URL = "https://myurl.com";
private static final String USERNAME= "myuser";
private static final String PASSWORD= "mypass";
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get(MY_URL);
Alert alert = driver.switchTo().alert();
Robot robot = new Robot();
Thread.sleep(1000);
type(robot, USERNAME);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(1000);
type(robot, PASSWORD);
alert.accept();
}
public static void type(Robot robot, String characters) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection stringSelection = new StringSelection( characters );
clipboard.setContents(stringSelection, null);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
}
}
No comments:
Post a Comment