Reputation: 43
I am trying to open a new tab in Chrome using Keys.CONTROL + "t" but its not working. Here's the code
System.setProperty("webdriver.chrome.driver", "C:/Downloads/New folder/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
After executing the script, chrome is launched and google.com is loaded, but new tab is not being opened.
OS: Win-10
Selenium version: selenium-java-3.13.0
Chrome Version: Version 68.0.3440.84 (Official Build) (64-bit)
Is it some issue with selenium 3.13.0 or am i doing something incorrectly.
PS: I tried using JavascriptExecutor and it is working fine. I need to know why driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
is not working properly.
Thanks in advance
Upvotes: 2
Views: 2123
Reputation: 4739
Try this answer it is working fine for me
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:/Users/sankalp.gupta/Desktop/JAVASELN/chromedriver.exe");
System.out.println("Ready to launch the browser");
WebDriver driver = new ChromeDriver();
driver.get("http://yahoo.com");
((JavascriptExecutor)driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("http://google.com");
}
}
Upvotes: 2
Reputation: 674
Here's the code to open a new tab/window and Check if a new tab is open. If open, switch to that window.
windows1 = driver.window_handles
driver.execute_script('window.open()')
windows2 = driver.window_handles
new_windows = list(set(windows2) - set(windows1))
if len(new_windows) == 0:
print 'ERROR: no new tabs found'
elif len(new_windows) > 1:
print 'ERROR: multiple new tabs found: ' + new_windows
else:
new_window = new_windows[0]
driver.switch_to_window(new_window)
Upvotes: 0
Reputation: 296
Try with robot class
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
Upvotes: 0
Reputation: 910
You can try following:
//Simulate pressing many keys at once in a "chord".
String openNewTab = Keys.chord(Keys.CONTROL, "t");
driver.findElement(By.cssSelector("body")).sendKeys(openNewTab);
Let me know, if you are still facing any issues.
Upvotes: 0