Reputation: 11
I am working on 2 URLS . I need to open the first URL ,perform some action and open the second URL.
openURL1() { perform action }
openURL2() { perform action } switch back to URL1
when I use driver.get or driver.navigate , URL1 gets closed. Is there anyway to retain the window with URL1 while opening URL2? I am working with selenium and JAVA
Upvotes: 0
Views: 2604
Reputation: 193058
Here is the Answer to your Question:
Here is the working code block which opens the URL http://www.google.com
, prints Working on Google
on the console, opens http://facebook.com/
in a new tab, prints Working on Facebook
in the console, closes the tab which opened the URL http://facebook.com/
, gets you back to the tab which opened the URL http://www.google.com
and finally closes it.
System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
String first_tab = driver.getWindowHandle();
System.out.println("Working on Google");
((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");
Set<String> s1 = driver.getWindowHandles();
Iterator<String> i1 = s1.iterator();
while(i1.hasNext())
{
String next_tab = i1.next();
if (!first_tab.equalsIgnoreCase(next_tab))
{
driver.switchTo().window(next_tab);
System.out.println("Working on Facebook");
driver.close();
}
}
driver.switchTo().window(first_tab);
driver.close();
Let me know if this Answers your Question.
Upvotes: 1
Reputation: 68
You may use javascript to open new tab
(JavascriptExecutor(driver)).executeScript("window.open();");
Upvotes: 1
Reputation: 118
If the second tab is not opened through an action that is performed in first tab, then you can use two driver objects, so that you'll have control of both the browsers with different driver objects.
WebDriver driver = new ChromeDriver();
driver.get("https://news.ycombinator.com");
WebDriver driver1 = new ChromeDriver();
driver1.get("https://www.google.com");
By this approach you can use driver to control URL1 and driver1 to control URL2.
Upvotes: 3