How to open a new tab using Selenium WebDriver?
I want to open multiple links in new tabs. This is to achieve to finish off the build validation tasks as soon as possible. So, that in every new tab all smoke test related links could be opened and then within each tab which corresponds to a smoke test requirement, we can carry out the sanity test.
Instead of opening a new browser, you can simply use the code below to open a new tab in the same browser: String selectLinkOpeninNewTab = Keys. chord(Keys. CONTROL,"t"); driver.
open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values. Approach: To open a new tab, we have to use _blank in the second parameter of the window.
Open a New Tabget('https://selenium.dev'); // A new tab is opened and switches to it await driver. switchTo(). newWindow('tab'); // Loads Sauce Labs open source website in the newly opened window await driver. get('https://opensource.saucelabs.com/');
Code:
WebDriver wd = new FirefoxDriver();
wd.get("http://www.gmail.com");
wd.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
wd.manage().window().maximize();
//To open a new tab
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
//To switch to the new tab
ArrayList<String> tabs = new ArrayList<String>(wd.getWindowHandles());
wd.switchTo().window(tabs.get(1));
//To navigate to new link/URL in 2nd new tab
wd.get("http://facebook.com");
The only way to open links in new tabs is by simulating key-board shortcuts. The following hold true in FFX, Chrome & IE
Selenium doesn't (currently) have any concept of tabs within a browser window, so in order to open the tab and then test it you HAVE to use option 3.
The following code will execute option 3. and then immediately close that new tab. (In C#)
new Actions(WebDriver)
.KeyDown(Keys.Control)
.KeyDown(Keys.Shift)
.Click(tab)
.KeyUp(Keys.Shift)
.KeyUp(Keys.Control)
.Perform();
new Actions(WebDriver)
.SendKeys(Keys.Control + "w")
.Perform();
You could also use:
.MoveToElement(tab)
.Click()
in the middle of the first option, and
.KeyDown(Keys.Control)
.KeyDown("w")
.KeyUp("w")
.KeyUp(Keys.Control)
in the second one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With