I have the following problem: When I run my code I want to open new tab(not link in new tab) but after I open it I can't focus on it. The focus is still on the old one. Here is my code:
WebDriver driver = new ChromeDriver();
driver.get("url for the initial tab");
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 15);
// Open tab for email generation
String url = "url for tab 2";
((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", url);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String site = driver.getCurrentUrl();
if(driver.findElements(By.xpath("xpath here")).size() != 0){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
System.out.println("Current URL:" + site); //I get the initial url.
Also after I focus on the new tab how to switch to the old one? Thanks
Here is the Answer to your Question:
I have used your own code and rewritten it with a few tweaks to work with the WindowHandles
using Set
from java.util
. Now your code opens https://google.com
first, prints the Page Title
, then opens the URL https://www.facebook.com/
in a new tab shifts its focus to the new tab with the URL https://www.facebook.com/
, prints the Page Title
and the current URL:
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Q44970997_newTabURL
{
public static void main(String[] args)
{
String site = null;
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://google.com");
driver.manage().window().maximize();
System.out.println(driver.getTitle());
String first_tab = driver.getWindowHandle();
String url = "https://www.facebook.com/";
((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", url);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
site = driver.getCurrentUrl();
Set<String> tab_handles = driver.getWindowHandles();
Iterator<String> itr = tab_handles.iterator();
while(itr.hasNext())
{
String next_tab = itr.next();
if(!first_tab.equalsIgnoreCase(next_tab))
{
driver.switchTo().window(next_tab);
System.out.println(driver.getTitle());
site = driver.getCurrentUrl();
System.out.println("Current URL:" + site); //You get the new url.
}
}
}
}
Let me know if this Answers your Question.
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.