John John - 5 months ago 20
Java Question

Selenium throws IndexOutOfBoundsException while opening new tab

Selenium Java program throws IndexOutOfBoundsException exception when executed below code to open new tab in Chrome.

Java Code:

System.setProperty("webdriver.chrome.driver", "/Users/john/Desktop/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
String baseUrl = "http://google";
driver.get(baseUrl);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");

ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1)); // switches to new tab
driver.get("https://www.facebook.com");


Error:

Starting ChromeDriver 2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b) on port 48571
Only local connections are allowed.
May 12, 2017 12:54:14 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at test.SeleniumTest.main(SeleniumTest.java:31)

Answer Source

The size of tabs is 1. You try to access position 1, while the highest possible is 0.