Opening link in new tab works for Firefox but doesn't work for Chrome browser using Selenium
I have a test where I need to open a link in a new tab. This should work in Firefox and Chrome. I tried it first using the Gmail link on the google page.
It works fine in Firefox, Gmail opens in a new tab. But in Chrome, the Gmail page opens in the same window and the menu stays open after right-clicking. Has anyone faced this problem?
Below is my sample code.
Firefox code:
FirefoxProfile myprofile;
ProfilesIni profile = new ProfilesIni();
myprofile = profile.getProfile("SeleniumAuto");
WebDriver driver = new FirefoxDriver(myprofile);
driver.get("http://www.google.com");
driver.manage().window().maximize();
Actions a = new Actions(driver);
WebElement e = driver.findElement(By.xpath("/html/body/div/div[3]/div[1]/div/div/div/div[1]/div[2]/a"));
a.moveToElement(e);
a.contextClick(e).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER).build().perform();
Chrome code:
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
WebDriver driver = new ChromeDriver(options);
driver.get("http://www.google.com");
driver.manage().window().maximize();*/
Actions a = new Actions(driver);
WebElement e = driver.findElement(By.xpath("/html/body/div/div[3]/div[1]/div/div/div/div[1]/div[2]/a"));
a.moveToElement(e);
a.contextClick(e).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER).build().perform();
source to share
I faced the same problem. Apparently ARROW_DOWN won't work, so I tried using a keyboard shortcut and it works for me. The code looks like this:
1) opening in a new tab with focus still on the current tab
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(your_path)));
actions.keyDown(Keys.CONTROL).perform();
driver.findElement(By.xpath(your_path)).click();
actions.keyUp(Keys.CONTROL);
2) by opening a new tab and navigating to a new tab
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(your_path)));
actions.keyDown(Keys.CONTROL).perform();
actions.keyDown(Keys.SHIFT).perform();
driver.findElement(By.xpath(your_path)).click();
actions.keyUp(Keys.SHIFT);
actions.keyUp(Keys.CONTROL);
Hope it helps.
source to share
Yes, you can easily do this using Selenium. Use the keyboard shortcuts (Ctrl + T) to open a new tab and then use the Ctrl + Tab (Ctrl + \ t) command to switch to the newly opened tab and do whatever you need to do. It will be like this
//open a new tab
WebElement e= driver.findElement(By.cssSelector(abc)).sendKeys(Keys.Control + "t");
//switch control to new tab
e.sendKeys(Keys.Control + "\t");
{
perform some function here
enter code here
}
//switch back to old tab
e.sendKeys(Keys.Control + "\t");
This will work if the browser only has two tabs open, because then it will use the Tab key to move between the two open tabs.
Hope it helps.
source to share