简体   繁体   中英

Switch between tabs in Mozilla using Selenium

I am using Selenium with Java, and I am using this code to switch between tabs in Mozilla, but it is opening a new window instead of a new tab. How do solve this, or is there another way to switch between tabs?

WebDriver shiva=new FirefoxDriver();
shiva.manage().window().maximize();
shiva.get("http://www.naukri.com/");
Thread.sleep(3000);
shiva.findElement(By.xpath("/html/body/div[1]/div/ul[1]/li[2]/a")).click(); 
shiva.findElement(By.xpath("/html/body/div[1]/div/ul[1]/li[1]/a")).sendKeys(Keys.CONTROL +"\t");  

Try to use this code:

ArrayList<String> tabs = new ArrayList<>(webDriver.getWindowHandles());
webDriver.switchTo().window(tabs.get(1)); // id of the tab

Your code should be below for switching between Tabs: Assert the relevant tab based on pageTitle (I Guess)

shiva.findElement(By.xpath("/html/body/div[1]/div/ul[1]/li[1]/a")).sendKeys(Keys.CONTROL + Keys.PAGE_DOWN);

If you wish to switch between windows then use

driver.switchto().window(windowhandle);

Also I wonder how are you able to open multiple Tabs?

Use firefox version 80.0 or above

I think it is a bug and it is resolved in firefox 80.0

I too had the same issue(using firefox version- 78.0 back then) but once i changed the version to 80 or above,it worked flawlessly

In a normal firefox window, a new window is opened in a new tab, if you go to settings --> General --> Tabs you will see an option Open new window in new tab instead 在此处输入图片说明

But when Selenium Webdriver launches a firefox profile, this option isn't selected by default so it opens in a new window instead of a new tab.

在此处输入图片说明

If you want to open a new tab, you need to create a different firefox profile with this option enabled and then you can launch the created profile

There is another way by which you can switch to a different tab.

Set<String> listOfTabs = driver.getWindowHandles();
// This code will return a set with all the window ids
// Then you can switch on any of the window.
driver.switchTo.window("String Id of window");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM