'How to switch to a new window in through Selenium

I have 1 3rd party integration as Paypal. When I will click on Place Order button it will navigate me from Place Order page to paypal page. Can you please let me know how it will be work. I have tried below code and I will redirect to Paypal Page but new window gets appears instead of same page. Please let me know how I will able to stay on same screen.

String handle= driver.getWindowHandle();
System.out.println(handle);
driver.findElement(By.name("New Message Window")).click();
Set handles = driver.getWindowHandles();
System.out.println(handles);
for (String handle1 : driver.getWindowHandles()) {
    System.out.println(handle1);
    driver.switchTo().window(handle1);
}


Solution 1:[1]

To switch to a new window you need to induce WebDriverWait with ExpectedConditions set as numberOfWindowsToBe() as follows:

String parent_handle= driver.getWindowHandle();
System.out.println(parent_handle);
driver.findElement(By.name("New Message Window")).click();
new WebDriverWait(driver,10).until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> handles = driver.getWindowHandles();
System.out.println(handles);
for(String handle1:handles)
    if(!parent_handle.equals(handle1))
    {
        driver.switchTo().window(handle1);
        System.out.println(handle1);
    }

Solution 2:[2]

I have a test environment for selenium using protractor within which there will be a driver indicating the webdriver. I am using the selenium-webdriver npm package in my js code and I have a function that switches between the old and new tab/popup :

goToTab(driver, tab) {
    if (tab !== 1 || tab !== 0) {
      throw new Error(`Tab ${tab} doesn't exist`);
    }
    return driver
      .then(() => driver.getAllWindowHandles())
      .then((handles) => {
        driver.switchTo().window(handles[tab]);
      })
      .catch((err) => {
        console.error('error in goToTab: ' + err);
        throw err;
      });
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 PersianIronwood