I'm not talking about the popups like alert, confirm or prompt dialogs. In the application if I click on a button popup gets opened. I am not able to switch the WebDriver to the popup window.
I've tried to use getWindowHandles() but it only returns the main window handle.
I also tried switchTo.window("windowname") but it didn't work.
Usually Modular Windows are part of the same DOM, unlike javascripts alerts. Only thing that sets them apart from rest of the page is that they are in different frame.
Try to see if this Modular Window lies inside a frame or iframe tag. If any of the parent is frame or iframe then you will have to change the context to that frame before you can performa any action on the Modal Window.
So find the frame do a driver.switchTo().frame() and then perform the action on the element you want to. Once the action is done, which would most probably bring you back to the main page. Use driver.switchTo().defaultContent() to bring focus back to main page.
This SO question will be helpful.
If this does not work it would be helpful to have a look at the page or its HTML.
//handle of the master window before clicking the link
String master = driver.getWindowHandle();
driver.findElement(By.linkText("Click me")).click();
//logic for waiting for the popup, checking the size to become greater than 1 or breaking after sometime to avoid the infinite loop.
int timeCount = 1;
do
{
driver.getWindowHandles();
Thread.sleep(200);
timeCount++;
if ( timeCount > 50 )
{
break;
}
}
while ( driver.getWindowHandles().size == 1 );
//Assigning the handles to a set
Set<String> handles = driver.getWindowHandles();
//Switching to the popup window.
for ( String handle : handles )
{
if(!handle.equals(master))
{
driver.switchTo().window(handle);
}
}
Are you using pageobjects?
If you are using this, you will need to find the elements after the popup appears, because initElements will not initialize them if they are not visible when you first open the page.
Assuming your talking about a javascript alert.
final Alert a = driver.switchTo().alert();
a.accept();
or
Execute JavaScript directly to handle the altert
and
Maybe wait for the alert to show up
As per webdriver this issue is fixed in 2.16 but still it does not work
Support for window.ShowmodalDialog
You can use Java Robot class for handling such cases.
Example :
Wait(5000); // Wait for model pop,
int keyInput[] =
{
KeyEvent.VK_S, KeyEvent.VK_E, KeyEvent.VK_L, KeyEvent.VK_E,
KeyEvent.VK_N, KeyEvent.VK_I, KeyEvent.VK_U, KeyEvent.VK_M,
};
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_TAB);
for (int i = 0; i < keyInput.length; i++)
{
robot.keyPress(keyInput[i]);
robot.delay(100);
}
robot.delay(1000);
robot.keyPress(KeyEvent.VK_TAB);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_TAB);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_TAB);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_ENTER); // Save Btn
The delay between events is necessary otherwise you will miss the events.
Related
In my app, I need to zoom out and then find out the web element.
I zoom out using Robot robot = new Robot(). It zoomed out successfully. After that, it doesn't find the web element. I tried with an explicit wait.
Robot robot = new Robot();
Thread.sleep(5000);
System.out.println("About to zoom out");
for (int i = 0; i < 3; i++) {
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_CONTROL);
}
new WebDriverWait(driver,50).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(prop.getProperty("mpath"))))
.click();
WebElement module1 = driver.findElement(By.cssSelector(prop.getProperty("msite")));
module1.click() ;
I don't know your case exactly, but here's what I would try to do if I were you.
1. Try to zoom out the browser in a different way.
Instead of using Robot class, try to use:
element.sendKeys(Keys.chord(Keys.CONTROL, "-")) (Keys.COMMAND on MacOS).
You could also try out Actions class if this doesn't work.
2. Consider looking for that element again, after the resize.
Not sure how it works during resizing of a page, but I know that after the refresh, WebElement's id might change, which might cause your problem.
Anyway, if none of these work, try to post the error code so we can try to help you.
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());
Is it possible to check whether the File Download Dialog Box in IE is visible using Selenium WebDriver or any other Java Library?
I don't want to download the file. I'm unable to verify the visibility of the dialog box.
Also I'm unable to close the dialog box.
Any help?
Check if your IE UNEXPECTED_ALERT_BEHAVIOR is set to IGNORE
try{
//Click the link that brings up the download dilaog
// Perform your next step : This is where the script will throw the excpetion due to the modal dialog.
}
catch(Exception e){
if(e.getMessage().contains("Modal dialog present")) {
System.out.println("A modal dialog is present. (which can be a download dialog)" );
System.out.println(e.getMessage());
// the exception message includes text contained in the dialaog. You can use it for validaton.
//Use a java robot class to cancel the dialog
Robot robot= new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
//Since the current focus is on cancel.. else use robot.keyPress(KeyEvent.VK_TAB) as needed.
}
I am using selenium web driver with java.
And developing automation for my app in facebook, so whenever I add my app for first time in facebook, it is asking for permissions with okay button
I am trying to click on okay button with my code but that is not working.
Is there a better way to click on okay button using selenium web driver with java?
What I tried is:
1)driver.findElemenr(element).click();
2)Actions action = new Actions(driver);
action.click(element)
3)Actions action = new Actions(driver);
action.moveToElement(element).click()
4)Actions action = new Actions(driver);
action.KeyDown(element, Keys.ENTER);
Please let me know the reason before if you want to downvote my question
I think you are looking for isEnabled() method in Selenium. What you can do is, after you click the button using webdriver you can check the status of the button and repeat the click process if the button is still enabled.
You just try with logic something like below.
int i=0;
while(isElementPresent(button) && i<10)
{
Thread.sleep(1000);
driver.findElement(button).click();
i++;
}
The above code will try to click on button until it present or i (int i)reached 10. (loop breaking point)
You can find isElementPresent method implementation here.
you can try this,
WebDriverWait button = new WebDriverWait(driver,60);
button.until(ExpectedConditions.elementToBeClickable(element));
button.click();
This will wait 60 secs for the button to be clickable,if condition (element is clickable) is met before 60 secs, well and good, button will be clicked, else an exception will be thrown...
ExpectedConditions class provides many useful methods.
We are using webdriver for our functional tests. But our application uses the showModalDialog JS function a lot to open a popup. When we try to test this functionality with webdriver it hangs from the moment the popup is opened.
We tried several things to test this:
Using the workaround explained here. But this seems to be a fix for selenium and not for webdriver. We tried it but it didn't work.
Searching for a good alternative, HtmlUnit opened the modal dialog and could interact with it, but it has it's drawbacks like no visual help to fix certain tests and it stopped execution when it detected a JS error in a JS library we have to use but have no control over.
How can we test this or work around this problem?
From my experiences with various automation tools interaction with "webpage dialog" windows opened from IE using window.showModalDialog() or window.showModelessDialog() is not available.
Since the window is not a "true" window (look at the taskbar, it doesn't even show up) most tools can't "inspect" it and/or interact with it.
However if you do find a tool that will, please advise - there are many people looking for such a beast.
That all said, if you can possibly avoid using either of these 2 proprietary methods you'll have much more luck.
(and yes, for the picky ones, Firefox and Chrome have adopted these kind of dialogs but they don't work quite the same)
None of the answers answer the question. If the driver hangs, then you can't call any methods on it. The question is NOT about finding the pop up, it is about how to stop the driver hanging. The only way I have found is to not use showModalDialog. This can be done by adding the folowing to your test code :
((JavascriptExecutor) driver).executeScript("window.showModalDialog = window.open;");
which calls window.open each time your JavaScript calls window.showModalDialog.
I am using webdriver.SwitchTo().Window() method but my concern is my popup window does not have "Name"
When I use webdriver.WindowHandles it return only one handle, I am using this statement after popup window open.
As I don't have name / handle I cannot switch from parent window to child window.
Any other solution to do the same functionality
First we have to switch to the active element:
driver.switchTo().activeElement();
To check whether we have actually switched to the correct active element:
driver.switchTo().activeElement().getText();
Even if the window doesn't have name u can use
driver.switchTo.defaultcontent();
and perform the operation you want to execute
or else you can get the window handle name using the below command
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle); }
hope this should work for you.
Issue 284 is for WebDriver. It seems that it will be implemented only after Issue 27 will be implemented, so the fix should be in Beta 1 or 2 of WebDriver.
Set<String> beforePopup = driver.getWindowHandles();
Set<String> afterPopup = driver.getWindowHandles();
afterPopup.removeAll(beforePopup);
if(afterPopup.size()==1){
System.out.println(afterPopup.toArray()[0]);
}
driver.switchTo().window((String) afterPopup.toArray()[0]);
What I have been using and it works great for us on with IE and Firefox is to go through popups
and look for a a unique text on the popup you are trying to interact with. Here is the method, let me know if it works for you. Please note the line driver = driver.switchTo().window(windowHandle);
public void switchWindow(String containingText, WebDriver driver) throws Exception {
if ( StringUtils.isEmpty(containingText))
return;
int counter = 1;
int numOfpopups = driver.getWindowHandles().size();
System.out.println("Waiting for popup to load..... # handles:" + numOfpopups);
while ( numOfpopups < 2 && ((counter%10) != 0) ) {
counter++;
try{Thread.sleep(1000);}catch (Exception e) {}
}
System.out.println("Done waiting for..... " + counter + " seconds");
if (driver.getWindowHandles().size() < 2)
throw new BrowserException("Timeout after " + counter + " secs. No popup present. ");
System.out.println("Going through window handles...");
for (String windowHandle : driver.getWindowHandles()) {
driver = driver.switchTo().window(windowHandle);
if ( driver.getPageSource().contains(containingText)
return;
else
continue;
}
throw new Exception("Window containing text '" + containingText + "' not found");
}
To my knowledge, webdriver has no built-in functionality to handle modal windows as of now. Webdriver will hang once you click button which opens modal window. This happens due to JS on parent window halts until child window is closed.
To handle modal windows such as this one, see below for possible workaround written in Java. The main idea is to perform action that opens modal window (click on the button) in new thread.
/**
* Click button to open modal window and switch to it
* #param we webElement handle of a button
*/
public void clickToOpenModal(final WebElement we) {
//Get handles of all opened windows before opening modal window
Set<String> initWindowHandles = getDriverInstance().getWindowHandles();
//Create new thread and click button to open window
Thread thread1 = new Thread() {
#Override
public void run() {
//Click button
click(we);
}
};
thread1.start();
//Wait for window to appear
waitForWindow(initWindowHandles, pauseL);
thread1.interrupt();
thread1 = null;
//Get handles of all opened windows after opening modal window
Iterator<String> it = getDriverInstance().getWindowHandles().iterator();
//Select handle of modal window
String windowHandle = "";
while(it.hasNext()){
windowHandle = it.next();
}
//Switch focus and work on the modal window
getDriverInstance().switchTo().window(windowHandle);
}
The solution by Hugh Foster works, i tried this and succeeded
((JavascriptExecutor) driver).executeScript("window.showModalDialog = window.open;");
You can find the url of modal dialog then open it on another tab, it will work as normal.
In case you want to deal with open modal dialog, you can try to send "tab" key for move around objects and "send keys... enter" for setText or click.
Note: Below is some information why you cannot use selenium webdriver for work with that modal.
Modal pop-up - This is very specific to IE, Microsoft defined it as
When Windows Internet Explorer opens a window from a modal or modeless HTML dialog box by using the showModalDialog method or by using the showModelessDialog method, Internet Explorer uses Component Object Model (COM) to create a new instance of the window. Typically, the window is opened by using the first instance of an existing Internet Explorer process. When Internet Explorer opens the window in a new process, all the memory cookies are no longer available, including the session ID. This process is different from the process that Internet Explorer uses to open a new window by using the open method.
http://msdn.microsoft.com/en-us/library/ms536759(VS.85).aspx
MSDN blog on Modal dialog
When user select Model popup, parent window is blocked waiting for the return value from the popup window. You will be not able to see the view source of the page, need to close the popup then only the parent window is activated.