I wanna close the pop up window (known window name), and back to the original window.
What shall I do?
If I can't get a constant of the close button in window. so is there any general behavior to reach the goal?
Using WebDriver (shown with Java) you could do something like this:
// instantiate your driver
...
// get window handle
String baseWindowHdl = driver.getWindowHandle();
// navigate to pop-up
...
// close pop-up
driver.close();
// switch back to base window
driver.switchTo().window(baseWindowHdl);
Have you tried:
selenium.Close();
selenium.SelectWindow("null");
I dont know if you are still looking for an answer, but i had some troubles with this.
After spending more than one hour on searching for a way to do it, dont want to use webdriver. I tried using the garbage collector:
Selenium selenium = new DefaultSelenium(......);
selenium.start();
................
selenium.close(); //to terminate testing window
selenium = null; //make sure there are no references to the file
System.gc(); //now the garbage collector can kick in
This worked for me.
Related
In my batch execution, multiple browsers with multiple tabs are getting opened for first scenario. I wanted to close all these browsers before starting second scenario.
Driver.close() is just closing one tab of the browser.
Driver.quit() is closing all the browsers and also ending the WebDriver session. So , am unable to run the batch execution. Please provide a solution for this.
You should understand difference between driver.close() and driver.quit()
driver.close() and driver.quit() are two different methods for closing the browser session in Selenium WebDriver. Understanding both of them and knowing when to use which method is important in your test execution.
driver.close() – It closes the the browser window on which the focus is
set.
driver.quit() – It basically calls driver.dispose method which in turn
closes all the browser windows and ends the WebDriver session
gracefully.
You should use driver.quit() whenever you want to end the program. It will close all opened browser window and terminates the WebDriver session. If you do not use driver.quit at the end of program, WebDriver session will not close properly and files would not be cleared off memory. This may result in memory leak errors.
In your case you have to use driver.close() which will close current window and keeps driver active.
Just to add - if there is only browser window open and you use driver.close(), it will quit the webdriver session. The webdriver will not stay active.
The below explanation should explain the difference between driver.close and driver.quit methods in WebDriver. I hope you find it useful.
driver.close and driver.quit are two different methods for closing the browser session in Selenium WebDriver.
Understanding both of them and knowing when to use each method is important in your test execution. Therefore, I have tried to shed some light on both of these methods.
driver.close - This method closes the browser window on which the focus is set. driver.quit close the session of webdriver while
driver.close only close the current window on which selenium control is present but webdriver session not close yet, if no other window open and you call
driver.close then it also close the session of webdriver.
driver.quit – This method basically calls driver.dispose a now internal method which in turn closes all of the browser windows and
ends the WebDriver session gracefully.
driver.dispose - As mentioned previously, is an internal method of WebDriver which has been silently dropped according to another answer - Verification needed. This method really doesn't have a use-case in a normal test workflow as either of the previous methods should work for most use cases.
Explanation use case: You should use driver.quit whenever you want to end the program. It will close all opened browser windows and terminates the WebDriver session. If you do not use driver.quit at the end of the program, the WebDriver session will not close properly and files would not be cleared from memory. This may result in memory leak errors.
............
Now In that case you need to specific browser.
Below is code which will close all the child windows except the Main window.
String homeWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
//Use Iterator to iterate over windows
Iterator<String> windowIterator = allWindows.iterator();
//Verify next window is available
while(windowIterator.hasNext())
{
//Store the Recruiter window id
String childWindow = windowIterator.next();
}
//Here we will compare if parent window is not equal to child window
if (homeWindow.equals(childWindow))
{
driver.switchTo().window(childWindow);
driver.close();
}
Now here you need to modify or add the condition according to your need
if (homeWindow.equals(childWindow))
{
driver.switchTo().window(childWindow);
driver.close();
}
Currently it is checking only if home window is equal to childwindow or not. Here you need to specify the condition like which id's you want to close. I never tried it so just suggested you the way to achive your requirement.
This code closes all the opened windows and then brings back control to the main window.
public static void switchTab() {
try {
Set<String> windows = webDriver.getWindowHandles();
Iterator<String> iter = windows.iterator();
String[] winNames=new String[windows.size()];
int i=0;
while (iter.hasNext()) {
winNames[i]=iter.next();
i++;
}
if(winNames.length > 1) {
for(i = winNames.length; i > 1; i--) {
webDriver.switchTo().window(winNames[i - 1]);
webDriver.close();
}
}
webDriver.switchTo().window(winNames[0]);
}
catch(Exception e){
e.printStackTrace();
}
}
My problem was, that when I opened a lot of URLs in the loop, I got a lot of open windows that are memory- and processor-consuming.
Attempt to use webDriver.close() in the end of a loop resulted in org.openqa.selenium.NoSuchSessionException: Tried to run command without establishing a connection - webDriver called quit() cause only one window was opened in first loop run (look top answer for explanation).
Final solution:
if (webDriver.getWindowHandles().size() > 1){
webDriver.close();
}
I have written a test case using WebDriver, I closed the browser in one method and again I am opening the browser not able to invoke
driver.close();i closed the browser through above command for again opening a browser i driver.get(url)
but i am getting error
'Error communicating with the remote browser It may have died'
If you really want to close the browser before navigating to the new URL, then do:
driver.quit();
driver = new FirefoxDriver();
driver.get(url);
However, why would you want to close the browser before navigating to the new URL in the first place?
I can think of either one of two reasons:
You want to go to the next URL with your browser's history cleaned.
If this is indeed the case, then deleteAllCookies will do the job.
You cannot go to the next URL because some popup alert is preventing you doing it.
If this is indeed the case, then neither close not quit will do the job.
Well you killed the browser with your driver.close();
In order to use the driver you must create a new one using something like driver = new FirefoxDriver(capabilities);
Moving to answer from comment.
I think I got your issue. Though you have called the close() and it only should close the current window, you should use this if you want to shift between multiple windows.
For your case just don't close the driver it will use the same window to open the url.
You have to use following way if you want to close the current browser and open
a new one:
webDriver.Close();
//Goto the Target website
WebDriver.Navigate().GoToUrl("url");
And you can use following way if you want to close the browser and kill the
web driver:
webDriver.Close();
webDriver.Quit();
My company wants me to develop a "Visual" GUI style BDD function using JBehave and Selenium, which uses javascript alert/confirm popup window to prompt user what is the exact step the running test reaches, eg:
Given I goto "www.google.com"
When I login
So we want to add Javascript alert window to popup during the automation test, the popped up window has the "OK" button, so when user click the OK button, the test will continue to the next step, and so on...
My issue is: I wrote a javascript func using Selenium's executeScript API which invoke the pop up alert window:
public void stepText(String step) {
executeScript("alert('"+step+"');");
}
So I expect when I click the OK button, the popped up window will disappear and test will continue to next step... But what shocked me is that when I click it, the test throw exception and crashed...
The exception is: selenium.WebDriverException
But I found if I add the following code to make the test automatically detect the alert window and accept it by using the following usual selenium alert handle function:
Alert alert=switchTo().alert();
alert.accept();
This can make the test runs well, so it looks I can NOT manually click the alert (after I manually click, the selenium still can NOT go back to the browser...lost connection to browser?), but the automation alert handle code works...
Of course, we want to let user to manually to click alert window to control the test execution, not the automation handle alert.
I really got stuck here for a while, and did a lot googling to search, but can not find similar example online, I hope you can shed me light on it, since you are much more guru than me on JBehave and Selenium.
I will be much grateful if you can help me out.
Selenium is a browser automation tool, it does not anticipate user's interactions.
Therefore, I'd use a simple Java GUI window to present the user with messages/options. Afterall, you are testing a web application in a browser, but the program itself is Java and has nothing to do with the browser. A usual Swing option dialog should be enough.
JOptionPane.showMessageDialog(null, "Login successful.");
String loginAs = JOptionPane.showInputDialog("Login as:", "admin");
int choice = JOptionPane.showConfirmDialog(null, "Use production data?");
(note that you don't want to invoke this in the EventQueue.invokeLater() block, because you want the dialogs to be blocking)
This way, you won't interact with Selenium or the browser in any way, you won't confuse it and you'll get the user input cleanly.
That said, if you insist on using alerts, I think it's definitely doable, but as of now (June 2013, Selenium 2.33.0), I don't know how:
The issue is not reproducible on IE8. After the executeScript("alert('Something.')"); call, Selenium waits for the call to return something and then proceeds normally. So you're good on IE.
However, with FF21, Selenium fails immediatelly with UnhandledAlertException just as you said.
I tried two obvious solutions:
js.executeScript("alert('something')");
new WebDriverWait(driver, 10)
.pollingEvery(100, TimeUnit.MILLISECONDS)
.ignoring(UnhandledAlertException.class)
.until(ExpectedConditions.not(ExpectedConditions.alertIsPresent()))
.wait();
and
js.executeScript("alert('something')");
boolean alertVisible = true;
while (alertVisible) {
try {
driver.switchTo().alert();
} catch (NoAlertPresentException ignored) {
alertVisible = false;
}
}
Both make FF fail horribly with an internal JavaScript exception. Possibly a bug that might get fixed (please test it, check whether it had been reported and report it if you're interested in it), so I'll leave the solutions here for future generations.
But as I said before, it's possible that it won't get fixed, since Selenium doesn't count on manual user interactions.
Not sure how this behaves in other browsers.
I have this problem with a text field that is visible at the time of the SendKeys. I'm using IEDriverServer.exe and C#.
Here's how I can reproduce the problem:
The text field in question is visible in the window but you have to scroll down to see it. To scroll down I click on the element using code like this:
var element = driver.FindElement(By.Xpath("…"));
element.Click();
This scrolls the window down and makes the text field visible.
But when I try to send text to now-visible window:
element.SendKeys("blah");
I get the exception:
When_applicant_enters_application.Should_be_instantly_approved_on_external threw exception: OpenQA.Selenium.ElementNotVisibleException: Element is not displayed
How can I fix or workaround this problem?
Selenium version: 2.32.1
OS: Windows 7
Browser: IE
Browser version: 9.0.15
I've written code demonstrating the problem and submitted it to the Selenium tech support volunteers.
The full discussion is at http://code.google.com/p/selenium/issues/detail?id=5620
but the take-home is:
// Doesn't work
// driver = new InternetExplorerDriver();
// driver.Navigate().GoToUrl(#"D:\CGY\selenium\Bug5620\Bug5620\Bug5620.htm");
// Works
// driver = new FirefoxDriver();
// driver.Navigate().GoToUrl(#"D:\CGY\selenium\Bug5620\Bug5620\Bug5620.htm");
// Works
driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl(#"http://localhost:8080/Bug5620/"); // Hosted on Tomcat
so there may be a problem that possibly involves IE, IE security settings, Visual Studio local servers and/or the IE Driver. This may not even be a code problem, but something that needs to be documented, since other people are apparently running into the problem.
I don't know where the problem is exactly but I do have a work-around at this point, which is to use the Firefox Driver.
Thanks for your help, Jim. If you find out a better way of dealing with the problem, please add an answer here for the other folks.
How could I start a Selenium browser (like Firefox) minimized? I want the command browser.start(mySettings) to start a browser minimized.
I have an alternate solution that may meet your needs. You can set the position of the WebDriver to be outside of your view. That way, it'll be out of sight while it runs. (It may start at a visible location, but it will only be there for an instant.)
FirefoxDriver driver = new FirefoxDriver();
driver.manage().window().setPosition(new Point(-2000, 0));
Your question does not say that why you want to run your test cases in minimized browser but unfortunately selenium do not provide any built-in function for the same.
Normally when we want to run test cases with maximized browser we use driver.manage().window().maximize();
No doubt there are several ways to minimize your window through code by using Java key event by using keyboard shortcuts for minimimzing window or by using JavaScriptExecuter but that too depend on which OS and language you are working.
One more thing you can try is HtmlUnitDriver.By using this you cant even see the browser, so that may also serve your purpose if you have a case of not opening the browser while execution of test cases.
Dimension windowMinSize = new Dimension(100,100);
driver.manage().window().setSize(windowMinSize);
For C# you can minimize window easily, also with a built in way.
See: https://www.selenium.dev/documentation/en/webdriver/browser_manipulation
Screenshot:
Without knowing your motive for minimizing the browser and assuming that you are using the WebDriver drivers (Selenium v2) and don't want a UI to pop up, one could use the lightweight browser HtmlUnitDriver.
After you define the driver
driver = webdriver.Chrome(r"FULL PATH TO YOUR CHROMEDRIVER")
Do
driver.minimize_window()
And then call the site
driver.get(r'SITE YOU WANT TO SELECT')
It will minimize.
When Using Python to Move the FireFox Browser off screen:
driver = webdriver.FireFox()
driver.set_window_position(-2000,0)
driver.set_window_position(2000,2000)
or
(x,y) values more than monitor resolution
Later if u want to see the window again
driver.maximize_window()
The workarounds mentioned in the post did not work for NodeWebKit browser, so as a workaround i had to use native C# code as mentioned below:
public static void MinimiseNWKBrowser(IWebDriver d)
{
var body = UICommon.GetElement(By.TagName("body"), d);
body.Click();
string alt = "%";
string space = " ";
string down = "{DOWN}";
string enter = "{ENTER}";
SendKeys.SendWait(alt + space);
for(var i = 1; i <= 5; i++)
{
SendKeys.SendWait(down);
}
SendKeys.SendWait(enter);
}
So this workaround basically uses "ALT+SPACE" to bring up the browser action menu to select "MINIMIZE" from the options and presses "ENTER"
In php we can use JavaScript command to minimize the browser window.
$this->selenium->getEval("Minimize();");
and similar command for java :
browser.getEval("Minimize();");
The best way to minimize your browser is to use shortcut using Robot class.
Shortcut: Alt+Space+N (for Windows)
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_N);
By using above code you can minimize your browser.
Selenium doesn't have a built-in method to minimize the Browsing Context. Minimizing the browser while the Test Execution is In Progress would be against the best practices as Selenium may loose the focus over the Browsing Context and an exception may raise during the Test Execution. You can find a relevant detailed discussion in How to execute tests with selenium webdriver while browser is minimized
However, to mimic the functionality of minimizing the Browsing Context you can use the following steps:
Set the dimension of the Browsing Context to [0, 0]
Set the position of the top left corner of the Browsing Context just below the Viewport
Code Block (Java):
driver.navigate().to("https://www.google.com/");
Point p = driver.manage().window().getPosition();
Dimension d = driver.manage().window().getSize();
driver.manage().window().setSize(new Dimension(0,0));
driver.manage().window().setPosition(new Point((d.getHeight()-p.getX()), (d.getWidth()-p.getY())));
You can use:
driver.manage().window().maximize();
For example code snippet with chrome driver:
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
driver = new ChromeDriver();
baseUrl = "chrome://newtab/";
driver.manage().window().maximize().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
for Firefox use just "firefordriver.exe"
driver.manage().window().minimize();
This should help minimize the window. You can also use "maximize" in place of "minimize" to maximize the window.