I am using Selenium and Java to write a test for Chrome browser. My problem is that somewhere in my test, I download something and it covers a web element. I need to close that download bar (I cannot scroll to the element). I searched a lot and narrowed down to this way to open the download page in a new tab:
((JavascriptExecutor) driver).executeScript("window.open('chrome://downloads/');");
It opens that new tab, but does not go to download page.
I also added this one:
driver.switchTo().window(tabs2.get(1));
driver.get("chrome://downloads/");
but it didn't work either.
I tried:
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL + "t");
and
action.sendKeys(Keys.CONTROL+ "j").build().perform();
action.keyUp(Keys.CONTROL).build().perform();
Thread.sleep(500);
but neither one even opened the tab.
It is because you can't open local resources programmatically.
Chrome raises an error:
Not allowed to load local resource: chrome://downloads/
Working solution is to run Chrome with following flags:
--disable-web-security --user-data-dir="C:\chrome_insecure"
But this trick doesn't work with Selenium Chrome Driver(I don't know actually why, a tried to remove all args that appears in chrome://version, but this doesn't helps).
So for me above solution is the only one that works:
C# example:
driver.Navigate().GoToUrl("chrome://downloads/")
There is another trick if you need to open downloaded file:
JavaScript example:
document.getElementsByTagName("downloads-manager")[0].shadowRoot.children["downloads-list"]._physicalItems[0].content.querySelectorAll("#file-link")[0].click()
Chrome uses Polymer and Shadow DOM so there is no easy way to query #file-link item.
Also you need to execute .click() method with JavaScript programatically because there is a custom event handler on it, which opens actual downloaded file instead of href attribute which point to url where you downloaded file from.
I started with this post and ended up with the solution given below. This one works in Chrome 71. First I highlighted the control and then clicked it.
The window object is actually the IWebDriver, the second method is called after the first one.
internal void NavigateToDownloads()
{
window.Navigate().GoToUrl("chrome://downloads/");
}
internal void OpenFirstDownloadLinkJS()
{
IJavaScriptExecutor js = (IJavaScriptExecutor) window;
js.ExecuteScript("document.getElementsByTagName('downloads-manager')[0].shadowRoot.children[4].children[0].children[1].shadowRoot.querySelectorAll('#content')[0].querySelector('#details > #title-area > #file-link').setAttribute('style', 'background: yellow;border: 2px solid red;');");
js.ExecuteScript("document.getElementsByTagName('downloads-manager')[0].shadowRoot.children[4].children[0].children[1].shadowRoot.querySelectorAll('#content')[0].querySelector('#details > #title-area > #file-link').click();");
}
Use this code (I wrote it in Python, but it should work in Java too with very slight modifications):
#switching to new window
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[1])
#opening downloads
driver.get('chrome://downloads/')
#closing downloads:
driver.close()
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.
I'm developing a GWT web App . Righ now I have one default EntryPoint: AppWeb.
The page works perfectly if I run it in the web browser:
http://localhost/AppWeb.
If I open a new tab, and write the same URL, the App works just fine as two instances.
Now, I just want that a simple button in my app open a new windows of the same app and same entry point, just like a new instance. But is not working. I'm using this:
Window.open("AppWeb?guiId=xxx", "_blank", "");
The problem is that the new tab is openen, but is not calling the onModuleLoad of the AppWeb entry point.
I think you could do it using an anchor http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/Anchor.html
Set the anchor target with
myAnchor.setTarget("_blank");
in your code and in the ui
<g:Anchor ui:field='my anchor' href='' text='click here to duplicate'/>
Note the empty href='' (because it would be appended to your current url).
I tried it and it calls onModuleLoad() when the entry point is called on the 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);
}
i am new learner of java i want to create one application program in applet. i want to create
"applet which has a Text Field to accept a URL string, and displays the document of the URL string in a new browser window."
Thanks in advance.
#nimit parekh
this post contains answer to your question:
Getting java gui to open a webpage in web browser
From inside your applet class (which must extend java.awt.Applet or javax.swing.JApplet):
getAppletContext().showDocument(new URL("http://www.google.com"));