daisy
daisy

Reputation: 89

How to Open new browser Window without closing previous window using selenium webdriver

I'm using below code to open new browser window but it is opening link in the same tab :-( . I want to open new browser window with clearing all cookies without closing first one window.

    `      Actions act = new Actions(driver);
    act.keyDown(Keys.CONTROL).sendKeys("N").build().perform();
    driver.get("https://www.facebook.com");`

I tried this code too but it did't help me out : Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_N); driver.get("https://www.facebook.com");

Any help would be appericated !!

Upvotes: 0

Views: 3438

Answers (3)

Osanda Deshan
Osanda Deshan

Reputation: 1559

First thing is your key combination to open a new window is incorrent. Correct key combination would be Control + N

And when you open the new window, you need to focus to that new window

You can use the below code snippet to open a new browser window and navigate to an url. This is using Robot class in java.awt.Robot package.

public void openNewWindow(String url) throws AWTException {

    // Initialize the robot class object
    Robot robot = new Robot();

    // Press and hold Control and N keys
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_N);

    // Release Control and N keys
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_N);

    // Set focus to the newly opened browser window
    ArrayList <String> tabs = new ArrayList<String> (driver.getWindowHandles());
    driver.switchTo().window(tabs.get(tabs.size()-1));
    for (String windowHandle : driver.getWindowHandles()) {
        driver.switchTo().window(windowHandle);
    }

    // Continue your actions in the new browser window
    driver.get(url);
}

Upvotes: 1

Kuldeep Kamune
Kuldeep Kamune

Reputation: 169

You can use below java script to open new window:

((JavascriptExecutor)driver).executeScript("window.open(arguments[0])", "URL to open");

Upvotes: -2

Ali Azam
Ali Azam

Reputation: 2115

To launch a new instance of the browser, implement the below code sample:

// Store the current window url
String url = driver.getCurrentUrl();

// Create a new instance to open a new window
WebDriver driver2 = new FirefoxDriver();    // Use your own browser driver that you are using

// Go to the intended page [i.e, foo or some other link]
driver2.navigate().to(foo);

// Continue your code here in the new window...

// Close the popup window now
driver2.quit();

// No need to switch back to the main window; driver is still valid.
// demonstrate that the initial driver is still valid.
url = driver.getCurrentUrl();

Upvotes: 0

Related Questions