Selenium | Opening and closing browser tabs with Key controls

|
| By Webner

We can use Robot class to open and close tabs in Selenium but we also have the Key_Control concept. These are keyboard shortcuts to open and close the tabs in browser :

Ctrl+t (Open New tab)
Ctrl+w (Close tab)

We can use these keyboard shortcuts in Selenium script also like below :

dr.manage().window().maximize();
//open a URL in default browser tab if needed
dr.get("http://www.google.com");
dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Open a new browser tab with control+t
dr.findElement(By.cssSelector("body")).
sendKeys(Keys.CONTROL + "t");

//open a URL in new browser tab if needed
dr.get("http://www.gmail.com");
dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//Close browser tab
dr.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "w");
dr.close();

Leave a Reply

Your email address will not be published. Required fields are marked *