Unable to set focus on pop up - java

[![enter image description here][1]][1]HTML code is shown in Screenshot [![enter image description here][2]][2]
I tried with Action class
WebElement element = InspectationOrder.wd.findElement(By.xpath("//div[#class='qx-window']"));
Actions actions = new Actions(InspectationOrder.wd);
actions.moveToElement(element).click().build().perform();
but found "java.lang.NullPointerException" while i tried to move focus.
but same action code works for other area in application
Also tried with
for (String popup : wd.getWindowHandles())
{
wd.switchTo().window(popup);
}
but not working :(
May be issue with z-index but m don't have more idea about the same .

(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
boolean bool = (Boolean) ((JavascriptExecutor)d).executeScript("return $('.modal').is(':visible') ");
return bool;
}
});
Your Dialog is actually an div in an upper layer. This codes waits up to 10 seconds until the dialog is created and show completely. Inside JavaScript is used to select the dialog and check weather is visible or not. (display: none). The result is returned. If the result is false your test will stop.

Can you please try adding an id to the div and use the below code?
driver.switchTo().frame(driver.findElement(By.id(id)));
driver.findElement(By.id(id inside popup));

Selenium latest version(Selenium 3 with GeckDriver ) automatically handles set focus.
Previously I am using selenium 2 in which we have to setfocus on new element.But in selenium 3 with GecoDriver we have no need to worry about small popups.
In my whole automation script selenium 3 handles setfocus[ Not fully but at basic level ] for me and works form me.
Use full links.
LINK-1
[LINK-2]
-Thanks
Dhaval

Related

Selenium - Text entered in same field, even though intended to type in different fields

Using selenium, when trying to enter username and password in login form, sometimes the text is entered on the same field. Username and password are having unique identifier.
For sending keys, the following steps are done.
sendKeys(By.id("login_username"), "abc");
sendKeys(By.id("login_password"), "efg");
public void sendKeys(By locator, String text) {
WebElement element = findElement(locator);
if(element != null) {
element.clear();
element.sendKeys();
}
}
public WebElement findElement(By locator) {
return wait(org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated(locator));
}
public WebElement wait(ExpectedCondition<WebElement> condition) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).pollingEvery(1, TimeUnit.SECONDS)
.withTimeout(60, TimeUnit.SECONDS)
.ignoreAll(Arrays.asList(NoSuchElementException.class, TimeoutException.class));
return wait.until(condition);
}
But somehow, when entering text, both the username and password texts are getting typed onto the password field. This is not happening always though. Not able to understand what could possibly go wrong or what to check. Any suggestions...
platform: Ubuntu 16.04.1 LTS 64-bit
chromedriver version: 2.25
chrome browser version: 55.0.2883.87
Thanks in advance.
The sendKeys() action performs the following steps:
Gets the coordinates of the element
Clicks at the coordinates it got (using a mouse action)
"Types" the text (that will be received by whatever element is currently focused)
It can go wrong if the element can't be focused when starting the action (because it's disabled for example), or if the coordinates change between getting the coordinates and clicking/focusing the element (because the layout is still changing).
Another common cause can be onClick action hooked on the element, that can lead to race conditions. Without seeing the actual page, it is possible that after selenium clicks, an onClick action is still working when the text is being typed. This basically looks like this:
Selenium clicks
onClick action starts (element might get focused only after it finishes)
Selenium starts typing (onClick haven't
returned yet, so the wrong elements gets the text)
the onClick
action finishes, but by that time Selenium finished too.
As a solution you can try focusing the element directly, and wait until it is really focused before sending the keys. This question might be of use for this case.

Selenium alert only shows in debug mode

I am testing a site page using Webdriver/Java which contains many fields. One of the fields is a dropdown box (or select box) and it contains validation upon losing focus (e.g. tabbing out). So if I select a particular option in the dropdown and tab to the next field, an alert box will pop up saying "You cannot choose that!".
Now I am doing code that checks for the presence of the alert box, and accepts it, however this is only working for me in DEBUG mode. When running the test (i.e. not in debug) I get "Timed out after 10 seconds waiting for alert to be present Build info: version: '2.53.0'".
I understand that this is probably a timing issue since it works in DEBUG mode, but I can't understand why as I'm using ExpectedConditions.alertIsPresent(). The code where this is failing is here:
WebElement currentElement = driver.findElement(By.id("selectbox"));
Select currentSelect = new Select(currentElement);
currentSelect.selectByVisibleText(updatedValue);
currentElement.sendKeys(Keys.TAB);
System.out.println("milestoneA");
if ((exceptionExpected()) {
System.out.println("milestoneB");
wait.until(ExpectedConditions.alertIsPresent());
System.out.println("milestoneC");
checkAlertBox(getExpectedResultFromExcel());
}
In DEBUG mode, the code keeps going fine and all is good. In RUN mode in my logs I get up to milestoneB and then the above mentioned error is thrown.
Further to this, if I add a Thread.sleep(1000) before Tabbing, all works fine.
Any ideas please?
I would try to send the TAB key until the element loses the focus:
WebElement currentElement = driver.findElement(By.id("selectbox"));
currentElement.click();
currentElement.sendKeys("abcd");
// wait for the popup to be visible
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#abc")));
// send the TAB key while the current element has focus
new WebDriverWait(driver, 20).until((WebDriver wd) -> {
currentElement.sendKeys(Keys.TAB);
return !wd.switchTo().activeElement().equals(currentElement);
});

How can I tell Selenium to press cancel on a print popup?

I am checking whether or not a page appears using Selenium. When I click the page, however, a printer print prompt appears (like the window that says select printer and such). How can I have Selenium close this window by hitting cancel?
I tried looking to alerts, but it seems like those will not work since the print window is a system prompt. It does not recognize any alerts appearing.
The most recent I tried using is by just sending keys like tab and enter in order to have the cancel button selected, however, it doesn't recognize any keys as being pressed.
How can I handle this case?
public static boolean printButton() throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get("website");
try {
Thread.sleep(3000);
WebElement temp = driver.findElement(By.xpath("//*[#id='block-print-ui-print-links']/div/span/a"));
temp.click();
Actions action = new Actions(driver);
action.sendKeys(Keys.TAB).sendKeys(Keys.ENTER);
Thread.sleep(6000);
}
catch (Exception e) {
System.out.println("No button.");
driver.close();
return false;
}
I would simply disable the print dialog by overriding the print method :
((JavascriptExecutor)driver).executeScript("window.print=function(){};");
But if you goal is to test that the printing is called then :
// get the print button
WebElement print_button = driver.findElement(By.cssSelector("..."));
// click on the print button and wait for print to be called
driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);
((JavascriptExecutor)driver).executeAsyncScript(
"var callback = arguments[1];" +
"window.print = function(){callback();};" +
"arguments[0].click();"
, print_button);
If you are going for testing only Chrome browser here is mine solution. Because of 'Robot' class or disabling print didn't work for my case.
// Choosing the second window which is the print dialog.
// Switching to opened window of print dialog.
driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());
// Runs javascript code for cancelling print operation.
// This code only executes for Chrome browsers.
JavascriptExecutor executor = (JavascriptExecutor) driver.getWebDriver();
executor.executeScript("document.getElementsByClassName('cancel')[0].click();");
// Switches to main window after print dialog operation.
driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());
Edit: In Chrome 71 this doesn't seem to work anymore since the script can't find the Cancel button. I could make it work by changing the line to:
executor.executeScript("document.querySelector(\"print-preview-app\").shadowRoot.querySelector(\"print-preview-header\").shadowRoot.querySelector(\"paper-button.cancel-button\").click();");
Actually you can't handle windows (OS) dialogs inside Selenium WebDriver.
This what the selenium team answers here
The current team position is that the print dialog is out of scope for
the project. WebDriver/Selenium is focused on emulating a user's
interaction with the rendered content of a web page. Other aspects of
the browser including, but not limited to print dialogs, save dialogs,
and browser chrome, are all out of scope.
You can try different approach like AutoIt
we can also use key for handling the print or press the cancel button operation. and it works for me.
driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());
WebElement webElement = driver.findElement(By.tagName("body"));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);
driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());
Native window based dialog can be handled by AutoItX as described in the following code
File file = new File("lib", jacobDllVersionToUse);
System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath());
WebDriver driver = new FirefoxDriver();
driver.get("http://www.joecolantonio.com/SeleniumTestPage.html");
WebElement printButton = driver.findElement(By.id("printButton"));
printButton.click();
AutoItX x = new AutoItX();
x.winActivate("Print");
x.winWaitActive("Print");
x.controlClick("Print", "", "1058");
x.ControlSetText("Print", "", "1153", "50");
Thread.sleep(3000); //This was added just so you could see that the values did change.
x.controlClick("Print", "", "2");
Reference : http://www.joecolantonio.com/2014/07/21/selenium-how-to-handle-windows-based-dialogs-and-pop-ups/
Sometimes 2 different statements as above (webElement.sendKeys(Keys.TAB)
webElement.sendKeys(Keys.ENTER)) will not work, you can use with combination of Tab and Enter keys as below, This will close the Print preview window.
Using C# :
Driver.SwitchTo().Window(Driver.WindowHandles[1]);
IWebElement element = Driver.FindElement(By.TagName("body"));
element.SendKeys(Keys.Tab + Keys.Enter);
Driver.SwitchTo().Window(Driver.WindowHandles[0]);
Erçin Akçay answer updated.
// Choosing the second window which is the print dialog.
// Switching to opened window of print dialog.
driver.switchTo().window(driver.getWindowHandles().toArray()[1].toString());
// Runs javascript code for cancelling print operation.
// This code only executes for Chrome browsers.
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector(\"body > print-preview-app\").shadowRoot.querySelector(\"#sidebar\").shadowRoot.querySelector(\"print-preview-button-strip\").shadowRoot.querySelector(\"div > cr-button.cancel-button\").click();");
// Switches to main window after print dialog operation.
driver.switchTo().window(driver.getWindowHandles().toArray()[0].toString());

The screen is not navigating even the click() method is executed successfully in mobile web app using selenium web driver

I was trying to click a button on my mobile web app, using selenium web driver. The button is located, the text over the button can be derived and even the click event is performing well. But the navigation doesn't occur.
I tried with Click() method, sendKeys() method and also with script executor. But couldn't process further on.
CODE:
public class TestWeb
{
WebDriver driver;
private Selenium selenium;
#Before
public void setUp() throws Exception {
driver = new IPhoneDriver();
driver.get("http://10.5.95.25/mobilebanking");
}
#Test
public void TC() throws Exception {
System.out.println("page 1");
Thread.sleep(5000);
WebElement editbtn1 = driver.findElement(By.id("ext-comp-1018"));
String s1 = editbtn1.getText();
System.out.println(s1);
editbtn1.click();
editbtn1.sendKeys(Keys.ENTER);
((JavascriptExecutor)driver).executeScript("arguments[0].click;", editbtn1);
System.out.println("ok");
}
#After
public void tearDown() throws Exception {
System.out.println("*******Execution Over***********");
}
}
I tried click, sendKeys and ScriptExecutor separately and also combined. It is executing without any error but the navigation doesn't occur.
Does anybody can help me with some other ways to perform click function on the button?
Ram
This may not be your issue but I noticed "ext-comp-" and guess you are using extjs.
I'm using GXT and while finding by id worked for many things, on some submit buttons it didn't.
I had to use firebug in firefox to locate the element and copy the xpath.
Then I could click the element by
driver.findElement(By.xpath("//div[#id='LOGIN_SUBMIT']/div/table/tbody/tr[2]/td[2]/div/div/table/tbody/tr/td/div")).click(); // worked
It was failing silently for me too. My submit button has the id of LOGIN_SUBMIT so I don't know why the following failed but ....
driver.findElement(By.id("LOGIN_SUBMIT")).click();//failed
Edit:
Here is an exact example (case 1 of 2):
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='gwt-debug-LOGIN_SUBMIT']")));
//wait.until(ExpectedConditions.elementToBeClickable((By.id("gwt-debug-LOGIN_SUBMIT")))); <!-- id works as well
OK so the element is found. It will timeout and throw an exception if it is not.
Still, the following fails (under firefox, works with chrome) with no error and the page does not navigate.
driver.findElement(By.xpath("//div[#id='gwt-debug-LOGIN_SUBMIT']")).click();
//driver.findElement(By.id("gwt-debug-LOGIN_SUBMIT")).click(); <-- fails too
What I have to do is:
driver.findElement(By.xpath("//div[#id='gwt-debug-LOGIN_SUBMIT']/div/table/tbody/tr[2]/td[2]/div/div/table/tbody/tr/td/div")).click();
So my experience was that even if I found the element with xpath, clicking failed unless I used a complete xpath.
Here is another exact example (case 2 of 2):
I can find an element like so:
WebElement we = driver.findElement(By.xpath("//*[#id=\"text" + i + "\"]"));
I know I have found it because I can see the text via:
we.getText();
Still selecting by the path I found it fails.
//get outta town man the following fails
driver.findElement(By.xpath("//*[#id=\"text" + i + "\"]")).click();
In this case there is not more explicit xpath to try as in case 1
What I had to do was use css:
//bingo baby works fine
driver.findElement(By.cssSelector("div#text" + i + ".myChoices")).click();
Actually, I obtained the css path via firebug than shortened it.
//this is what I recieved
html.ext-strict body.ext-gecko div#x-auto-0.x-component div#x-auto-1.x-component div#x-auto-3..myBlank div#choicePanel1.myBlank div.x-box-inner div#text3.myChoices //text3 is the id of the element I wanted to select
Whether or not you can figure out your needed xpaths and css selectors, I don't know, but I believe I experienced exactly what you did.

Can't select option with Selenium Webdriver

I have very strange problem. Using selenium I am writing simple web-bot trying to fill page with data, submit them, and harvest results.
I fill all the forms with no problems at all, but than I have to first enter the ZIP code, than click somewhere else for AJAX to list all the possibilities, than select the appropriate option (I want to always select the first one).
But my problem is, I simply can't select it. I fill the ZIP, click the option list itself, wait to "please select" message to get lost (by this time my choice should be there) and than selecting it. I tried option.click(), I tried selectByVisibleText(), and even the deprecated setSelected(). Nothing happens. All I see in FF is drop-downed list of option, with the first one being marked, but that's all. I tried many ways, with no luck at all.
There is my last-attempt code:
ZIPCode = driver.findElement(By.id("formparam_data2_zip")); //get and fill ZIP
ZIPCode.sendKeys(ZIP);
address = driver.findElement(By.name("formparam_data2_zip_id")); // click to fire AJAX
address.click();
(new WebDriverWait(driver, 20)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) { // wait until AJAX shows results
WebElement elm = d.findElement(By.id("formparam_data2_zip_id"));
List<WebElement> options = elm.findElements(By.tagName("option"));
for(WebElement w : options){
if(w.getText() != "Prosím, vyberte."){
return true;
}}
return false;
}});
List<WebElement> options = address.findElements(By.tagName("option"));
options.get(0).click(); // click first option - ! this failes !
phaseTwoBtn = driver.findElement(By.id("formparam_data2_next")); // than submit...
phaseTwoBtn.submit();
I had a similar problem and had better results using the Actions class and then making sure to use the moveToElement() method before clicking on it.
Actions builder = new Actions(d);
builder.moveToElement(options.get(0)));
builder.click();
builder.build().perform();
The moveToElement method makes sure the element is in the visible window
Using key board keys we can solve this problem in selenium webdriver .Code for the above example,ZIPCode.sendkeys (ZIP);ZIPCode.sendkeys (Keys.Tab);
ZIPCode.sendkeys (Keys.Return);
try this
if(!w.getText().equals("Prosím, vyberte.")){
return true;
}

Categories

Resources