I wants to open a new tab which contains a dynamic url. The url i am getting store in str variable as shown below:
String str = WebPublish_URL.getText();
.
Now I wants a tab with url by using getText()
method.
CodePudding user response:
.getText
is to get the text
from a web element. If your str
contains a URL
and you want to open a new tab and then load str containing URL
, try the below steps :
to open a new tab
((JavascriptExecutor) driver).executeScript("window.open()");
once it's opened up you would need to switch as well.
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
so basically, in sequence :
((JavascriptExecutor) driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get(str);
CodePudding user response:
There are 3 ways to do this. In below example,
- Launching
https://google.com
- Searching for
facebook
text and getting thefacebook
URL
- Opening
facebook
within and different tab.
Solution#1: Get the URL
value and load it in existing browser.
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
driver.get(facebookUrl);
Solution#2: Using window handles
.
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get(facebookUrl);
Solution#3: By creating new driver
instance. It's not recommended but it is also a possible way to do this.
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
/*Create an another instance of driver.*/
driver = new ChromeDriver(options);
driver.get(facebookUrl);