-1

I have been trying many functions to open a link in a tab I recently opened but it does not work.

Minimum reproducible example with commentary saying what happens after each line (this is using Selenium webdriver, Java):

driver.get("https://twitter.com") //opens twitter in tab 1(intended)

((JavascriptExecutor)driver).executeScript("window.open('https://google.com')"); //opens new tab (tab 2) then opens google.com(intended)
((JavascriptExecutor)driver).executeScript("window.location.replace('https://facebook.com')"); //opens facebook.com in tab 1 (unintended)

I want Facebook to open in tab 2 instead.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
IamTrying
  • 29
  • 8

1 Answers1

0

Once you open https://twitter.com as the base url and then open https://google.com in the adjascent tab. Next open the url https://facebook.com in the same adjascent tab you you have to induce WebDriverWait for numberOfWindowsToBe(2) and you can use the following solution:

  • Code Block:

    public class A_demo 
    {
        public static void main(String[] args) throws Exception 
        {
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
            options.setExperimentalOption("useAutomationExtension", false);
            WebDriver driver = new ChromeDriver(options);
            driver.get("https://twitter.com");
            String parent_window = driver.getWindowHandle();
            ((JavascriptExecutor) driver).executeScript("window.open('https://google.com');");
            new WebDriverWait(driver,5).until(ExpectedConditions.numberOfWindowsToBe(2));
            Set<String> allWindows = driver.getWindowHandles();
            for(String child_window:allWindows)
                if(!parent_window.equalsIgnoreCase(child_window))
                    driver.switchTo().window(child_window);
            driver.get("https://facebook.com");
            driver.quit();
        }
    }
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352