Friday, 3 January 2020

SE - 44 - How to open a new tab in a pre opened browser from selenium

There are 2 ways to open a new tab in browser which is previously opened.

1) Using Sendkeys method

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);

2) Using Robot class to send keyboard keys : Ctrl + T

//Launch the first URL
driver.get("http://www.google.com");
 
//Use robot class to press Ctrl+t keys     
Robot robot = new Robot();                          
robot.keyPress(KeyEvent.VK_CONTROL); 
robot.keyPress(KeyEvent.VK_T); 
robot.keyRelease(KeyEvent.VK_CONTROL); 
robot.keyRelease(KeyEvent.VK_T);
 
//Switch focus to new tab
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
 
//Launch URL in the new tab
driver.get("http://google.com");


3) Using JavaScrptExecutor

String link = "window.open('https://www.google.com','_blank');";
((JavascriptExecutor)driver).executeScript(link);
OR

((JavascriptExecutor) driver).executeScript("window.open();");

No comments:

Post a Comment