sendKeys to Textbox which you cannot Inspect (using Java) - java

I have this alert box with an textbox which cannot be inspected and in want to sendKeys to this textbot.
inspect absent
public void handleprompt() throws InterruptedException {
driver.get("http://www.tizag.com/javascriptT/javascriptprompt.php ");
driver.findElement(By.xpath("//input[#onclick='prompter()']")).click();
Thread.sleep(3000);
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("abcd");
}
There is no error but the text is not visible in text box or my code is incorrect

Hai Bro there is nothing wrong with your code i just simply copy pasted your code and executed it it works absolutely fine
public void handleprompt() throws InterruptedException {
driver.get("http://www.tizag.com/javascriptT/javascriptprompt.php ");
driver.findElement(By.xpath("//input[#onclick='prompter()']")).click();
Thread.sleep(3000);
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("abcd");
prompt.Accept();
}
After accepting the alert popup you are able to see the text you entered.

I removed the sleep (it's not a good practice) and instead added a wait for the Alert, sendKeys, and then accept. I noticed that I didn't see the text in the alert after sending but when the alert was accepted, it showed the "abcd" text.
public void handleprompt() throws InterruptedException {
String url = "http://www.tizag.com/javascriptT/javascriptprompt.php";
driver.get(url);
driver.findElement(By.xpath("//input[#onclick='prompter()']")).click();
Alert prompt = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
prompt.sendKeys("abcd");
prompt.accept();
}
I tested this code and it's working.

Related

How to handle intermittent alert in Selenium WebDriver?

I have automation scenario that sometimes the system return javascript alert and sometimes not at all. I don't know what the cause of this, probably the network issue. I already create the alert handler for this:
public boolean isAlertPresent() {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
I call this in one of my step that sometimes appear alert:
public WSSPage enterAndSearchContent(String title) throws InterruptedException {
waitForElementTextWithEnter(searchTextField, title);
while (isAlertPresent()){
Alert alert = driver.switchTo().alert();
alert.dismiss();
break;
}
return PageFactory.initElements(driver, WSSPage.class);
}
The problem is when the alert doesn't show up, it will give me NoAlertPresentException, and the automation result will be failed. I want the code to move on if the alert doesn't happen by moving to the next line, in this case it will just return PageFactory.initElements(driver, WSSPage.class);
Can you help me provide a better code from this?
Thanks a lot.
JavascriptExecutor worked for you. Just take care that you should execute it before clicking the event which invoke alert.
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
Note :- do not use it after clicking on event which invoke alert confirmation box. Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked
Hope it will help you :)
You can modify the method isAlertPresent as given below and try it. It may help you.
public boolean isAlertPresent() {
try{
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
catch (NoAlertPresentException noAlert) {
return false;
}
catch (TimeoutException timeOutEx){
return false;
}
}
You can include that particular exception in try catch. Then the exception will be catched and will not through any error and your execution will continue.
Also create a implicit wait to handle this with less timestamp.

When I run a selenium test for Firefox to create a user the test runs but I never see the user in my list

However, if I set up to run using Microsoft Edge the test completes and i can see the user just created in the list. Here is my code. Very confused.
As you can see all I change to run for Microsoft Edge is un-comment the setProperty line and then change the FirefoxDriver to EdgeDriver. When I do that as I said the script runs and upon completion I log in and can see the user in the list while when using this code I cannot see the user.
public static void main (String[] args) throws InterruptedException {
// System.setProperty("webdriver.edge.driver", "/Program Files (x86)/Microsoft Web Driver/MicrosoftWebDriver.exe");
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
baseUrl = "http://briotest.brio.viddler.com/";
firstName = "Sam";
lastName = "Bradford";
email = "sbradford#mail.com";
password = "Sooners1!";
test();
}
public static void test() throws InterruptedException {
// get to login page and enter credentials
driver.get(baseUrl + "/users/login");
driver.findElement(By.name("email_address")).clear();
driver.findElement(By.name("email_address")).sendKeys("jfayefrank#yahoo.com");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("*********");
driver.findElement(By.cssSelector("button.button")).click();
// Now on the assets view page. Go to Users and select Create
driver.findElement(By.xpath("/html/body/header/div[2]/nav/div/ul[1]/li[6]/a")).click(); // Users tab
driver.findElement(By.linkText("Create")).click();
// Enter new users credentials and submit
driver.findElement(By.id("email")).clear();
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("first_name")).clear();
driver.findElement(By.name("first_name")).sendKeys(firstName);
driver.findElement(By.name("last_name")).clear();
driver.findElement(By.name("last_name")).sendKeys(lastName);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(email);
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys(password);
try {
Thread.sleep(5000);
}
catch (Exception e) {
System.out.println("Could not perform pause");
}
// driver.findElement(By.cssSelector("input.button")).click();
driver.findElement(By.xpath("/html/body/div[1]/section/div/article/form/input[2]")).click();
System.out.println ("User created!!!");
}
Problem solved. Thanks to a coworker my problem is resolved. Apparently since Firefox was not maximized the Submit button was not really selected even though it appeared to do the action. Once I added driver.manage().window().maximize(); my users were now visible in the list. Did I mention the coworker was an intern...

How to handle Javascript Alert/pop up window in selenium webdriver

I am not sure whether selenium webdriver can handle Javascript alert/pop-up window.
I have a scenario like
1. User uploads a xls file and click on upload button
2. Alert/Pop-up window will be displayed . Click "OK" on window
Am able to automate the above scenario but the Alert/pop-up window is displayed while running the scripts.
Is their anyway workaround that we can handle javascript alert/pop-up window?
You can also try waiting for the alert to appear and then accepting it.
Below is the code for that (after the upload button is clicked):
try{
//Wait 10 seconds till alert is present
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
//Accepting alert.
alert.accept();
System.out.println("Accepted the alert successfully.");
}catch(Throwable e){
System.err.println("Error came while waiting for the alert popup. "+e.getMessage());
}
Switch to default content
Dismiss alert after accepting "OK"
Otherwise your alert is from a different window which you'll have to switch to in order to dismiss
driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();
driver.switchTo().alert().defaultConent();
Mock it out. Call javascript behind the UI directly:
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
}
There are the four methods that we would be using along with the Alert interface:
void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
String getText() – The getText() method returns the text displayed on the alert box.
void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
if(isAlertPresent(ldriver)){
Alert alert = ldriver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
Alert is a interface which have the abstract methods below
void accept();
void dismiss();
String getText();
void sendKeys(String keysToSend);
new WebDriverWait(driver,10).
until(ExpectedConditions.alertIsPresent()).accept();
alertIsPresent() internally return the
driver.switchTo.alert(); then we don't have to write it explicitly
hope this is been helpful

selenium webdriver modal dialog java

I am testing my form and when I don't type needed data I get javascript alert in my web app that tells the user to enter missing data. I can't handle this with selenium because when I partially fill form and try to submit I get exception
org.openqa.selenium.UnhandledAlertException: Modal dialog present
If I catch exception the alert in webdriver is not shown. Is that any solution to solve this issue?I would like to be able to submit form and catch the alert. I am using Linux Mint,Firefox 18 and selenium 2.28.0 with java
Best regards
UPDATE
I have following in my code
somePage.fillName(sth); //only 1 of 2 required field are filled
somgePage.submit(); //here js alert is shown right after clicking submit
somePage.getCurrentAlert();
//here are code parts
public Alert getCurrentAlert(){
return driver.switchTo().alert();
}
public AdminHome submit(){
saveUrl();
WebElement submit = driver.findElement(By.id("add_quiz_submit_button"));
try{
submit.click();
if(urlChanged()){
return new AdminHome(driver);
}
}
catch(Exception e){
e.printStackTrace();// exception 1
return null;
}
return null;
}
//Exception 1
org.openqa.selenium.UnhandledAlertException: Modal dialog present
//The test fails because of:
org.openqa.selenium.NoAlertPresentException: No alert is present (WARNING: The server did not provide any stacktrace information)
However if I click manual on submit the test work as expected. Thanks in advance
you should handle the alert as soon as the action is done and there shouldn't be any other action before handling the alert.
for instance your code should be
try{
submit.click();
if (alertPresent())
getCurrentAlert();
if(urlChanged()){
return new AdminHome(driver);
}
}
This will check alert and then accept the alert. The interaction of webdriver is more similar to the action we interact with manually with browser. So when the click on submit is done we will be able to see alert and no actions can be done until accept or reject it.
Vishal
It is because driver accepts the alert itself when the UnhandledAlertException is thrown. How can you submit the form if you have filled it partially?
If it is even possible, just catch that exception, and in catch block write the line which clicks on the submit button.
Use Robot class (Press enter) to close modal dialog box
try {
(new Robot()).keyPress(java.awt.event.KeyEvent.VK_ENTER);
(new Robot()).keyRelease(java.awt.event.KeyEvent.VK_ENTER);
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to Click a option in Security Warning dialog box using Selenium?

I've written a selenium code with java testng for submitting a form. After clicking submit button the page navigates to thankyou page. But before loading thankyou am getting a Security Warning dialog box which has the options called 'Continue' and 'Cancel'. How to click Continue through selenium control. There is no way for getting xpath or id of the continue button.
Had same problem, this worked for firefox 13 and selenium 2.0
Use spy to get the window info.
For firefox 13 windows class is MozillaDialogClass
WindowName is Security Warning.
declare import
[DllImport("user32.dll")]
public static extern int FindWindow(string className, string windowName);
make method
public static void SetOkButton(string className, string windowName)
{
int handle = FindWindow(className, windowName);
if (handle > 0)
{
if (SetForegroundWindow(handle))
{
SendKeys.SendWait("{ENTER}");
}
}
}
call the method
SetOkButton("MozillaDialogClass", "Security Warning");
Remember to add a wait before it appears otherwise your code may executed before alert actually appears. Following piece of code is working for me
private void acceptSecurityAlert() {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(3, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
Alert alert = wait.until(new Function<WebDriver, Alert>() {
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch(NoAlertPresentException e) {
return null;
}
}
});
alert.accept();
}
If that is a JS confirmation box on load of the page, then (as the docs say), you can't do much. Selenium 2 (WebDriver) can handle these dialogs in a much better way:
driver.switchTo().alert().accept();
If that is a Firefox confirmation, you can't do anything with Selenium.
I'd give java.awt.Robot a try.
There is no xpath or id of the 'Continue' button on the 'Security Warning' dialog as this dialog is not a browser dialog. This dialog was generated by Java.
Selenium only automates browsers. Hence, it is beyond the scope of Selenium to click on the 'Continue' button.
Thankfully there is a way to click on the 'Continue' button by taking the help of these jars: jna.jar and jna-platform.jar and java.awt.Robot class.
If you don't know when 'Security Warning' will appear, you can write code to wait until the 'Security Warning' appears. This code keeps checking for the current active window title. Once 'Security Warning' dialog appears, the currently active window will become 'Security Warning' dialog. The code then uses TAB key to navigate to 'Continue' button and presses ENTER key.
You can use the below method after doing the necessary imports:
public void acceptSecurityAlert() {
//Keep checking every 7 seconds for the 'Security Warning'
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(1000, TimeUnit.SECONDS).pollingEvery(7, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
//Wait until the 'Security Warning' appears
boolean isTrue = wait.until(new Function<WebDriver, Boolean>(){
//implement interface method
public Boolean apply(WebDriver driver) {
try {
char[] buffer = new char[1024 * 2];
HWND hwnd = User32.INSTANCE.GetForegroundWindow();
User32.INSTANCE.GetWindowText(hwnd, buffer, 1024);
//System.out.println("Active window title: " + Native.toString(buffer));
//Check for 'Security Warning' window
if(Native.toString(buffer).equalsIgnoreCase("Security Warning")){
//After 'Security Warning' window appears, use TAB key to go to 'Continue' button and press ENTER key.
//System.out.println("Pressing keys...");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB); robot.delay(200);
robot.keyRelease(KeyEvent.VK_TAB); robot.delay(200);
robot.keyPress(KeyEvent.VK_TAB); robot.delay(200);
robot.keyRelease(KeyEvent.VK_TAB); robot.delay(200);
robot.keyPress(KeyEvent.VK_ENTER); robot.delay(200);
robot.keyRelease(KeyEvent.VK_ENTER); robot.delay(200);
return true;
}
return null;
}catch(Exception e) {
System.out.println("Exception!");
e.printStackTrace();
}
return null;
}
});
}

Categories

Resources