How to change window selenium java? - java

I'm trying to access iframe inside html tag.xpath is not working.How to change my window to iframe in selenium(java/maven)?

First you need to create driver object and after you can switch windows by id, name and WebElement.Then driver object has functions for switch back to default window.like this example.
// create driver object
WebDriver driver = DriverManager.getDriver();
// change window using iframe id or iframe name
driver.switchTo().frame("frame id or frame name");
// change window using WebElement object
driver.switchTo().frame(webElement);
Switch back window
// switch back to main frame
driver.switchTo().parentFrame();
// switch back one frame
driver.switchTo().defaultContent();
Content copy from (read this article) selenium window change article.Impotent information's here.

Right Click on HTML Page the search there for iframe.
Get the frame ID, Name or index.
pass one of the above parameters into following command
driver.switchTo.Frame(" ID or Name Or index");
then try to use your xpath.

You can use: deiver.switchTo Method with the element locator, you can find more with the following: https://www.guru99.com/handling-iframes-selenium.html

Basically, the question is to change window we have java inbuild methods.
1. get.windowhandle(): This method helps to get the window handle of the current window
2. get.windowhandles():This method helps to get the handles of all the windows opened. It stores all the current active windows into set..
so if you get all the window handle you can do is example:
code:
Set<String> setLink = driver.get.windowhandles();
now you can simply do the indexing and switch.
ex.
driver.get(setLink[2]);
3. Another method to switch is using keyBoardkeys
String clickl = Keys.chord(Keys.CONTROL,Keys.TAB);
String clickl = Keys.chord(Keys.CONTROL,Keys.(Index of window you like 1,2,3));
// open the link in new tab, Keys.Chord string passed to sendKeys
driver.findElement(
By.xpath("any xpath")).sendKeys(clickl);

Related

Unclear about driver.getWindowHandles() & driver.getWindowHandle()

Hi all I am learning Selenium & I am not really clear about how the above two functions work:
Problem Statement:
I have a practice assignment say: Go to http://the-internet.herokuapp.com/
Click on a link> Multiple Windows A Window opens> Click on>> Click Here Another Window opens>> from this window grab text and print it After that go back to this http://the-internet.herokuapp.com/windows and print text.
Flow: http://the-internet.herokuapp.com/>>>http://the-internet.herokuapp.com/windows>>>http://the-internet.herokuapp.com/windows/new
Que1) If I use driver.getWindowHandle() and print it for each window its value remains constant so does this method always returns the parent window or it works differently.
Ques2) When I use driver.getWindowHandles() it is returning 2 values in the set. Does driver.getWindowHandles() return the parent window as well. (I am not sure if there should be 2 or 3 values as I have 3 URLS I thought the set should have 3)
Ques3) Can someone share the most effective way to work with multiple child window id's:
Set with iterator method
People also convert Set to Arraylist and then use get method. [which is a better way]
Code:
driver.get("http://the-internet.herokuapp.com/");
String p1=driver.getWindowHandle();
System.out.println(p1);
text1=driver.findElement(By.xpath("//a[#href='/windows']"));
text1.click();
WebElement
text2=driver.findElement(By.xpath("//a[#href='/windows/new']"));
text2.click();
Set<String> child=driver.getWindowHandles();
System.out.println(child.size());
ArrayList<String> children=new ArrayList<String>(child);
System.out.println(children);
driver.switchTo().window(children.get(1));
System.out.println(driver.findElement(By.xpath("//div[#class='example']/h3")).getText());
driver.close();
driver.switchTo().window(children.get(0));
System.out.println(driver.findElement(By.xpath("//div[#class='example']/h3")).getText());
driver.switchTo().window("");
System.out.println(driver.getCurrentUrl());
driver.close();
driver.get("http://the-internet.herokuapp.com/");
String p1=driver.getWindowHandle(); //Gets the newly opened and the only window handle
System.out.println("This is parent window handle " + p1);
text1=driver.findElement(By.xpath("//a[#href='/windows']"));
text1.click(); //Navigates, no new window opened. Handle remains the same
//WebElement 'Unnecessary code
text2=driver.findElement(By.xpath("//a[#href='/windows/new']"));
text2.click(); //opens second window/tab as per the settings. there are 2 window handles here for current driver instance
Set<String> child=driver.getWindowHandles(); //set of 2
System.out.println(child.size());
// ArrayList<String> children=new ArrayList<String>(child);' modifying this
String strSecondWindowHandle = "";
for(String str : s) // as set is not an ordered collection we need to loop through it to know which position holds which handle.
{
if(str.equalsIgnoreCase(p1) == false) //to check if the window handle is not equal to parent window handle
{
driver.switchTo().window(str) // this is how you switch to second window
strSecondWindowHandle = str;
break;
}
}
// System.out.println(children);
// driver.switchTo().window(children.get(1)); //not required
System.out.println(driver.findElement(By.xpath("//div[#class='example']/h3")).getText());
driver.close(); // now this will close the second window
driver.switchTo().window(p1); // switches to main window
System.out.println(driver.findElement(By.xpath("//div[#class='example']/h3")).getText());
// driver.switchTo().window(""); //not required as it is the same window
System.out.println(driver.getCurrentUrl());
driver.close(); //closes the main window
So to answer your questions
Window handle is automatically and uniquely assigned by the operating system (Windows) to each newly opened window
Q1 --> Until and unless you explicityly switch the windows, the window handle remains the same. switching is the key here.
Q2 --> Navigating does not change the handles. it is not page specific rather it is window specific. getWindowHandles will return all the open browser windows opened by WebDriver instances that is currently running. Already open windows are not included.
Q3 --> Using the for loop demonstrated above, you open the window, find the ID which is not your parent window handle, store it in a variable. Repeat the procedure for more windows.
You can see in the documentation what are the main differences between getWindowHandle() and getWindowHandles() methods:
getWindowHandle(): Return an opaque handle to this window that uniquely identifies it within this driver instance.
getWindowHandles(): Return a set of window handles which can be used to iterate over all open windows of this WebDriver instance by passing them to switchTo().WebDriver.Options.window()
In simpler terms, driver.getWindowHandles() stores the set of handles for all the pages opened simultaneously, but driver.getWindowHandle() fetches the handle of the web page which is in focus. It gets the address of the active browser and it has a return type of String.

Checking for URL in JUnit

I'm using the selenium RC driver for JUnit testing my application. Here is the relevant code I am trying to write. It checks that if the user clicks the link, they are taken to the right place.
selenium.click("//td[#id='myLink']/a");
String myURL = selenium.getLocation();
However, when the webdriver simulates a "click," it instead opens up a new window. So now I have the first window open, and the page that I wanted to navigate to is open in a seperate window. Now, when I try to get the URL, selenium grabs the first URL, so it fails the test case. How can I make the page open in the same window? Or, alternatively, how can I get selenium to check the URL of the new window?
EDIT: Should also mention, both my first and second window have the same title, so I don't think I can use selenium.SelectWindow(Title); for this.
Well, with selenium RC being as fickle as it is, I found a work-around for this problem. Here is the brief overview of how I changed my code:
String targetURL = selenium.getAttribute("//td[#id='myLink']/a#href");
selenium.openWindow(targetURL, "myNewWindow");
Thread.sleep(3000); //wait a few seconds for my page to load
selenium.selectWindow("myNewWindow");
selenium.getLocation();
//do my checks
selenium.selectWindow("originalWindowName");
So I retrieve the href myself, open the window using the retrieved URL and with my own custom name. I then switch the context of the driver to the new window and perform my checks. Once I am done, I switch my context back to the original window, and continue with my tests.

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();

selenium, how can I select new window

I run my selenium rc test in Eclipse with TestNG. I have a link which tries to open a new browser page. How can I select this new page to operate in? I use this code:
selenium.selectWindow("name=NewPage");
however it says page not found. I also try to define page ids or titles with this code:
String[] wins = selenium.getAllWindowIds();
for (String s : wins)
System.out.println("win: " + s);
It does not define my new opened window:
win: MainPage
win:
If use selenium.getAllWindowNames() I get win: selenium_main_app_window
win: selenium_blank65815.
I write this code selenium.selectWindow("name=blank99157"); but get the error - ERROR: Window does not exist. If this looks like a Selenium bug, make sure to read http://seleniumhq.org/docs/02_selenium_ide.html#alerts-popups-and-multiple-windows for potential workarounds.
The window obviously has no name, so you can't select it by name.
If the window is opened via JavaScript and you can change the script, try changing window.open("someUrl"); to window.open("someUrl", "someName");, you'll be then able to select the window by the set name. More information on the MDN doc for window.open().
Selenium RC doesn't support <a href="someUrl" target="_blank"> links (which open the link in a new window). Therefore, if the window is opened by a link of this type, you have to find this <a> element, get the href attribute and call
selenium.openWindow(theFoundUrl, "theNewWindow");
selenium.selectWindow("id=theNewWindow");
If it is opened via JavaScript before or during the onload event, you'll need to call
selenium.openWindow("", "theNewWindow");
selenium.selectWindow("id=theNewWindow");
More information on this in the bug SEL-339 or in the openWindow() and selectWindow() JavaDocs.
If you have only two windows / want to open the newest one, you can try
selenium.selectPopup()
That is, obviously, the easiest way, because it selects the first non-top window. Therefore, it's only useful when you want to select the newest popup.
If the new window has a unique title, you can do
selenium.selectPopup("Title of the window");
or selenium.selectWindow("title=Title of the window");
Otherwise, you must iterate over selenium.getAllWindowNames() to get the right name (Selenium creates names for windows without one). However, you can't hardcode that name into your testcase, because it will change every time, so you'll need to work out some dynamic logic for this.
You won't like this: Go for WebDriver. It should be far more resistant to such problems.
WebDriver driver = new FirefoxDriver();
WebElement inputhandler = driver.findelement(By.linktext("whatever here"));
inputhandler.click();
String parentHandle = driver.getWindowHandle();
Set<String> PopHandle = driver.getWindowHandles();
Iterator<String> it = PopHandle.iterator();
String ChildHandle = "";
while(it.hasNext())
{
if (it.next() != parentHandle)
{
ChildHandle = it.next().toString();
// because the new window will be the last one opened
}
}
driver.switchTo().window(ChildHandle);
WebDriverWait wait1 = new WebDriverWait(driver,30);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.id("something on page")));
// do whatever you want to do in the page here
driver.close();
driver.switchTo().window(parentHandle);
You might not be using the correct window ID.
Check out this link. You might find your answer here.
Let me know you this helps.
Try selenium.getAllWindowNames(), selenium.getAllWindowTitles()..one of them will work for sure.

WebDriver open new tab

I have trawled the web and the WebDriver API. I don't see a way to open new tabs using WebDriver/Selenium2.0 .
Can someone please confirm if I am right?
Thanks,
Chris.
P.S: The current alternative I see is to either load different urls in the same window or open new windows.
There is totally a cross-browser way to do this using webdriver, those who say you can not are just too lazy. First, you need to use WebDriver to inject and anchor tag into the page that opens the tab you want. Here's how I do it (note: driver is a WebDriver instance):
/**
* Executes a script on an element
* #note Really should only be used when the web driver is sucking at exposing
* functionality natively
* #param script The script to execute
* #param element The target of the script, referenced as arguments[0]
*/
public void trigger(String script, WebElement element) {
((JavascriptExecutor)driver).executeScript(script, element);
}
/** Executes a script
* #note Really should only be used when the web driver is sucking at exposing
* functionality natively
* #param script The script to execute
*/
public Object trigger(String script) {
return ((JavascriptExecutor)driver).executeScript(script);
}
/**
* Opens a new tab for the given URL
* #param url The URL to
* #throws JavaScriptException If unable to open tab
*/
public void openTab(String url) {
String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";
Object element = trigger(String.format(script, url));
if (element instanceof WebElement) {
WebElement anchor = (WebElement) element; anchor.click();
trigger("var a=arguments[0];a.parentNode.removeChild(a);", anchor);
} else {
throw new JavaScriptException(element, "Unable to open tab", 1);
}
}
Next, you need to tell webdriver to switch its current window handle to the new tab. Here's how I do that:
/**
* Switches to the non-current window
*/
public void switchWindow() throws NoSuchWindowException, NoSuchWindowException {
Set<String> handles = driver.getWindowHandles();
String current = driver.getWindowHandle();
handles.remove(current);
String newTab = handles.iterator().next();
locator.window(newTab);
}
After this is done, you may then interact with elements in the new page context using the same WebDriver instance. Once you are done with that tab, you can always return back to the default window context by using a similar mechanism to the switchWindow function above. I'll leave that as an exercise for you to figure out.
The Selenium WebDriver API does not support managing tabs within the browser at present.
var windowHandles = webDriver.WindowHandles;
var script = string.Format("window.open('{0}', '_blank');", url);
scriptExecutor.ExecuteScript(script);
var newWindowHandles = webDriver.WindowHandles;
var openedWindowHandle = newWindowHandles.Except(windowHandles).Single();
webDriver.SwitchTo().Window(openedWindowHandle);
I had the same issue and found an answer. Give a try.
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
It will open a new tab you can perform your actions in the new tab.
Though there is no API for opening a new tab, you can just create a new instance of WebDriver calling it something slightly different and passing the URL you want in the new tab. Once you have done all you need to do, close that tab and make the new driver NULL so that it does not interfere with the original instance of Webdriver. If you need both tabs open, then ensure you refer to the appropriate instance of WebDriver. Used this for Sitecore CMS automation and it worked.
Thanks for the great idea #Jonathan Azoff !
Here's how I did it in Ruby:
def open_new_window(url)
a = #driver.execute_script("var d=document,a=d.createElement('a');a.target='_blank';a.href=arguments[0];a.innerHTML='.';d.body.appendChild(a);return a", url)
a.click
#driver.switch_to.window(#driver.window_handles.last)
end
There's no way we can create new TAB or handle tabs using web driver / selenium 2.0
You can open a new window instead.
Hey #Paul and who ever is having issue opening a second tab in python. Here is the solution
I'm not sure if this is a bug within the webdriver or because it isn't compatible yet with mutlitab but it is definitely acting wrong with it and I will show how to fix it.
Issue:
well I see more than one issue.
First issue has to do that when you open a 2nd tab you can only see one handle instead of two.
2nd issue and here is where my solution comes in. It seems that although the handle value is still stored in the driver the window has lost sync with it for reason.
Here is the solution by fixing the 2nd issue:
elem = browser.find_element_by_xpath("/html/body/div[2]/div[4]/div/a") #href link
time.sleep(2)
elem.send_keys(Keys.CONTROL + Keys.RETURN + "2") #Will open a second tab
#solution for the 2nd issue is here
for handle in browser.window_handles:
print "Handle is:" + str(handle) #only one handle number
browser.switch_to_window(handle)
time.sleep(3)
#Switch the frame over. Even if you have switched it before you need to do it again
browser.switch_to_frame("Frame")
"""now this is how you handle closing the tab and working again with the original tab"""
#again switch window over
elem.send_keys(Keys.CONTROL + "w")
for handle in browser.window_handles:
print "HandleAgain is:" + str(handle) #same handle number as before
browser.switch_to_window(handle)
#again switch frame over if you are working with one
browser.switch_to_frame("Frame")
time.sleep(3)
#doing a second round/tab
elem = browser.find_element_by_xpath("/html/body/div[2]/div[4]/div/a") #href link
time.sleep(2)
elem.send_keys(Keys.CONTROL + Keys.RETURN + "2") #open a 2nd tab again
"""Got it? find the handle, switch over the window then switch the frame"""
It is working perfectly for me. I'm open for questions...
Do this
_webDriver.SwitchTo().Window(_webDriver.WindowHandles.Where(x => x != _webDriver.CurrentWindowHandle).First());
or Last() etc.
PS there is no guarantee that the WindowHandles are in the order displayed on your browser, therefore, I would advise you keep some history of current windows before you do the command to that caused a new tab to open. Then you can compare your stored window handles with the current set and switch to the new one in the list, of which, there should only be one.
#Test
public void openTab() {
//Open tab 2 using CTRL + t keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//Open URL In 2nd tab.
driver.get("http://www.qaautomated.com/p/contact.html");
//Call switchToTab() method to switch to 1st tab
switchToTab();
}
public void switchToTab() {
//Switching between tabs using CTRL + tab keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
//Switch to current selected tab's content.
driver.switchTo().defaultContent();
}
we can use keyboard events and automate opening and switching between multiple tabs very easily. This example is refered from HERE
I must say i tried this as well, and while it seemingly works with some bindings (Java, as far as Jonathan says, and ruby too, apparently), with others it doesnt: selenium python bindings report just one handle per window, even if containing multiple tabs
IJavaScriptExecutor is very useful class which can manipulate HTML DOM on run time through JavaScript, below is sample code on how to open a new browser tab in Selenium through IJavaScriptExecutor:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
object linkObj = js.ExecuteScript("var link = document.createElement('a');link.target='_blank';link.href='http://www.gmail.com';link.innerHTML='Click Me';document.getElementById('social').appendChild(link);return link");
/*IWebElement link = (IWebElement)linkObj;
link.Click();*/
browser.Click("//*[#id='social']/a[3]");
Just to give an insight, there are no methods in Selenium which would allow you to open new tab, the above code would dynamically create an anchor element and directs it open an new tab.
You can try this way, since there is action_chain in the new webdriver.
I'm using Python, so please ignore the grammar:
act = ActionChains(driver)
act.key_down(Keys.CONTROL)
act.click(link).perform()
act.key_up(Keys.CONTROL)
For MAC OS
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://google.com")
body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.COMMAND + 't')
Java Robot can be used to send Ctrl+t (or Cmd+t if MAC OS X) as follows:
int vkControl = IS_OS_MAC ? KeyEvent.VK_META : KeyEvent.VK_CONTROL;
Robot robot = new Robot();
robot.keyPress(vkControl);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(vkControl);
robot.keyRelease(KeyEvent.VK_T);
A complete running example using Chrome as browser can be forked here.
I would prefer opening a new window. Is there really a difference in opening a new window vs opening a new tab from an automated solution perspective ?
you can modify the anchors target property and once clicked the target page would open in a new window.
Then use driver.switchTo() to switch to the new window. Use it to solve your issue
Instead of opening new tab you can open new window using below code.
for(String childTab : driver.getWindowHandles())
{
driver.switchTo().window(childTab);
}

Categories

Resources