Ankita
Ankita

Reputation: 3

How to enter string in browser address bar by using getText() method, in selenium webdriver java

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.

Upvotes: 0

Views: 1005

Answers (2)

Nandan A
Nandan A

Reputation: 2922

There are 4 ways to do this. In below examples I am doing following steps,

  • Launching https://google.com
  • Searching for facebook text and getting the facebook 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);

Update with Selenium 4:

driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
driver.switchTo().newWindow(WindowType.TAB);
driver.navigate().to(facebookUrl);

Upvotes: 1

cruisepandey
cruisepandey

Reputation: 29362

.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);

Upvotes: 0

Related Questions