Selenium web driver | java | unable to switch between firefox browser windows - java

Using Selenium Webdriver 2. java.
I would like to switch back in forth between two firefox browser windows. When I do I get: org.openqa.selenium.NoSuchWindoException: Unable to loacate window"{accb1cc2-74c9-3b4e-8f71-c0b184a037c4}"; duration or timeout:
Here is the java:
driver = new FirefoxDriver();
driver.get("http://mail.google.com");
String firstWindowHandle = driver.getWindowHandle();
System.out.println("handle of first window ="+firstWindowHandle);
Thread.sleep(1000);
driver = new FirefoxDriver();
driver.get("http://www.google.com");
// Get names of currently open windows
String secondWindowHandle = driver.getWindowHandle();
System.out.println("handle of first window ="+secondWindowHandle);
Thread.sleep(1000);
// It fails right here!
driver.switchTo().window(firstWindowHandle );
driver.get("http://www.lifehacker.com");
It prints the following to the console:
- handle of first window = {accb1cc2-74c9-3b4e-8f71-c0b184a037c4}
- handle of the second window = {f5256619-a36e-a441-9979-937da0abacd1}
All help is appreciated.

Unfortunately, you cannot switch between windows the way you are currently trying to do it - WebDriver lost the first window as soon as you instantiated a new instance.
You could try opening the second window via javascript and then switching back and forth from it:
window.open('http://www.bing.com','Bing','modal=yes,alwaysRaised=yes')
This is a bit of a hack, and could have the following problems:
Popup blockers may prevent the action
The browser must have javascript enabled
Future browser versions may break the hack
Complaining and murmuring from peers (and perhaps rightly so) because even though it might work, it's still a hack ;)
Some final thoughts:
Is there any particular reason it has to be the same driver instance?
If not, just switch between two driver instances:
FirefoxDriver driver = new FirefoxDriver();
driver.get("http://mail.google.com");
FirefoxDriver driver2 = new FirefoxDriver();
driver2.get("http://www.google.com");

Swtiching between 2 active Windows:
FirefoxDriver wd=new FirefoxDriver();
wd.get("https://irctc.co.in/");
wd.manage().timeouts().implicitlyWait(5000,TimeUnit.SECONDS);
WebElement wb=wd.findElement(By.linkText("Cabs"));
wb.click(); //Now 2 Windows are open
wd.manage().timeouts().implicitlyWait(5000,TimeUnit.SECONDS); //Wait for the complete page to load
Set<String> sid=wd.getWindowHandles(); //getWindowHandles() method returns the ids of all active Windows and its return type will be a Collection Set.
Iterator<String> it=sid.iterator(); //Using iterator we can fetch the values from Set.
String parentId=it.next();
System.out.println(parentId);
String childId=it.next();
System.out.println(childId);
wd.switchTo().window(childId); //swtiching control to child Window
wd.close(); //control returns to the parent Window.

Related

Unable to locate the elements of SmartGWT application using Selenium in IE browser

I'm testing a GWT + SMARTGWT application like Paint and I'm trying to locate the elements of this web application using Selenium Webdriver. The method which I have used to locate the elements is by the relative XPath of those elements but the problem which I am currently facing is that this method is working correctly on the browsers like Chrome, Firefox, and Edge but not on the IE browser. The version of IE on my PC is 11.1593.14393.0. In the IE browser, this relative XPath method is giving a TimeOutException. I have given the explicit wait:
wait.until(ExpectedConditions.elementToBeClickable(webelement));
The IE browser is not able to find the element. I am also getting the following exception sometimes for other elements:
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: Unable to locate an element with the xpath expression //img[contains(#src,'Insert XXX'] because of the following error:
Error: Bad token: ]
Among the troubleshooting solutions to this issue, I tried enabling/disabling the protected mode in IE for all the levels but this method didn't work. Along with that, I also tried checking the box next to the option - "Allow active content to run files on My Computer" but this method also failed to work.
What should I do to fix my issue?
This is my code. Here firstly, I will click on the Insert button located on the top bar of the application and after clicking on the Insert button, a window will launch on which I will click on the Close button.
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.ie.driver", "D:\\SELENIUM\\Drivers\\iedriverserver.exe");
WebDriver driver = new InternetExplorerDriver();
Thread.sleep(3000);
driver.get(baseURL);
WebDriverWait wait = new WebDriverWait(driver, 10);
final String InsertPath = "//img[contains(#src,'Insert XXXX')]";
final String closePath="//img[contains(#src,'close')]";
WebElement Insert = driver.findElement(By.xpath(InsertPath));
wait.until(ExpectedConditions.elementToBeClickable(Insert));
Thread.sleep(2000);
Insert.click();
WebElement close = driver.findElement(By.xpath(closePath));
wait.until(ExpectedConditions.elementToBeClickable(close));
Thread.sleep(3000);
close.click();
}
}
Edit: I also used finding the element using Javascript executor in my code as follows:
WebElement Insert = driver.findElement(By.xpath(InsertPath));
Thread.sleep(2000);
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].click();", Insert);
Sadly, this method also failed to work in the IE browser.
So, I was able to locate the elements by using the latest driver of the Internet Explorer and giving the following desired capabilities in my code to the IE browser.
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability("requireWindowFocus", true);
ieCapabilities.setCapability("unexpectedAlertBehaviour", "accept");
ieCapabilities.setCapability("ignoreProtectedModeSettings", true);
ieCapabilities.setCapability("disable-popup-blocking", true);
ieCapabilities.setCapability("enablePersistentHover", true);*/
System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver(ieCapabilities);

Triggering events in chrome from java

Is it possible to interact with Chrome from within a java application? Say for example fill in an input field and submit/trigger a button event?
Yes. See WebDriver's ChromeDriver.
Example usage taken from docs:
// Optional, if not specified, WebDriver will search your path for chromedriver.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/xhtml");
Thread.sleep(5000); // Let the user actually see something!
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
Thread.sleep(5000); // Let the user actually see something!
driver.quit();

Selenium 2 + phantom js: unable to perform actions on a mouseover

I'm trying to perform an action on a button it's never done.
final Actions action = new Actions(mDriver);
final WebElement myCart = mDriver.findElement(By.cssSelector("path to my span"]"));
final WebElement myButton = mDriver.findElement(By.cssSelector("path to my button"));
action.moveToElement(myCart).build().perform();
action.moveToElement(myButton).click().build().perform();
This code works perfectly with firefox but not with phantom JS
I found some issue here How to handle Mouseover in Selenium 2 API or How to perform mouseover function in Selenium WebDriver using Java? but nothing work with phantom.
Is there any known workaround for this ?
Thanks!
I had similar issues when I used GhostDriver and PhantomJS around a year ago (FYI article). Actually I had problems with IE_Driver and Chrome_Driver too, mostly related with visibility of elements outside the screen_frame (page must be scrolled down).
One of most serious issues was the upload_window and handle it through already-mentioned. I wasn't able to achieve it doh. But my workaround was to switch/cast the driver on these problematic places and after they complete/handle the operation - switch it back to GhostDriver. Even by doing so, the execution speed was impressive.
Hope this helps - even late given.
Update:
find IWebElement to process
set WebDriver from GhostDriver to FirefoxDriver
process the IWebElement item with current WebDriver as FirefoxDriver
verify expected result from processing the IWebElement item
set back WebDriver from FirefoxDriver to GhostDriver
continue workflow
As far as I remember my Test framework implementation - a BaseTest class takes care of initialization of used WebDriver and ISelenium objects. So for your more specific case, you can try this:
// Create a new instance of the Ghost driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new GhostDriver();
//do stuff until new driver is needed
driver = new FirefoxDriver();
//do stuff with new driver
//'cast' back after required operations have been completed and verified
driver = new GhostDriver();

Selenium Java open new window, close it, and control main window again

I find my question to be different than everything that I've searched for because I need to open a new window in my code (not from clicking a link in a UI). So i already have a driver handling my only window, and then I do this:
//save the handle of the current (only) window open right now
String MainWindowHandle = driver.getWindowHandle();
//open a new firefox window
driver = new FirefoxDriver();
//in the new window, go to the intended page
driver.navigate().to(foo);
//do some stuff in the pop up window..
//close the popup window now
driver.close();
//switch back to the main window. This is where the error is thrown
driver.switchTo().window(MainWindowHandle);
The error is: "org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died"
What do I need to do to regain control of the initial window?
Thanks in advance.
You don't. If you need to launch a new instance of the browser (which is what this sounds like), then do that.
// "url" is an unused variable, simply included here to demonstrate
// that the driver variable is valid and capable of being used.
String url = driver.getCurrentUrl();
// Open a new Firefox window
// Note that here, in your original code, you've set the
// driver variable to another instance of Firefox, which
// means you've orphaned the original browser.
WebDriver driver2 = new FirefoxDriver();
// In the new window, go to the intended page
driver2.navigate().to(foo);
// Do some stuff in the pop up window..
// Close the popup window now
driver2.quit();
// No need to switch back to the main window; driver is still valid.
// Remember that "url" is simply a dummy variable used here to
// demonstrate that the initial driver is still valid.
url = driver.getCurrentUrl();

Webdriver hangs in new window with “about:blank” in address bar, transitioning to file download dialog

I need some help for the following issue using Webdriver, Java, and Firefox.
In the testing, when clicking on a link,
1) it will often open a new window with a normal web page. OR
2) occasionally, it will open a new window with “about:blank” in address bar; after 20 to 60 seconds the new window will disappear and a file download window will appear.
Because the URL is rewritten for SEO, there is no way to check the URL before or after clicking on the link to determine whether the link connects to a normal web page or a downloadable file.
In both cases,
driver.getWindowHandles().size() == 2,
so I can switch to the new window successfully using the following statements in order to check whether a certain WebElement exists in new window.
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
But if the link connects to a downloadable file, the execution will hang for any of the following methods:
findElement(By.xpath(“//html”));
findElements(By.tagName(“body”));
getCurrentUrl();
getPageSource();
getTitle();
getWindowHandle();
getWindowHandles() always returns 2 while new window with “about:blank” in address bar presents before it is replaced by the file download dialog. It occasionally throws a NoSuchWindowException exception; but most of the time, it just hangs. I tried the Explicit and Implicit Waits to no avail.
Many thanks
Sam
Have you tried setting the following preference? (This will get rid of the download dialog all together)
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.manager.showWhenStarting",false);
FirefoxDriver driver = new FirefoxDriver(profile);

Categories

Resources