Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getWindowHandle() Selenium Webdriver Javascript

Made some changes based on help from engineering. Here is the final code I used for grabbing the new window handle:

localdriver = @driver
@driver.getAllWindowHandles()
.then (handles) ->
    localdriver.switchTo().window(handles[1])

I'm currently running an automation stack that uses Selenium Webdriver, Mocha, Chai, and Grunt. I'm creating scripts in Coffeescript, but an answer to my question in Javascript would be perfectly fine.

What I'm trying to do:

  • Click button on main browser window
  • Switch driver to the second window that opens after button click
  • Perform actions in the second window
  • Close second window and return to the first.

I've scoured the internet looking for an answer on how to do this. Just started learning all this stuff a few months ago, and I'm still stumbling through creating stuff. I'm seeing a lot of Java and C+ examples, but not much on the Javascript side. Can anyone provide an example of how to set up the code for the above scenario using Selenium Webdriver and Javascript?

like image 893
bfriedrich Avatar asked May 31 '26 19:05

bfriedrich


2 Answers

var parent = driver.getWindowHandle();
var windows = driver.getAllWindowHandles();

driver.switchTo().window(windows[1]);

// do some stuff

driver.close();
driver.switchTo().window(parent);
like image 76
Rohn Adams Avatar answered Jun 02 '26 09:06

Rohn Adams


What you want is driver.getAllWindowHandles(), but because this returns a promise, make sure that you then use the handles inside of the then function

// select the newly opened window
driver.getAllWindowHandles().then(function gotWindowHandles(allhandles) {
    driver.switchTo().window(allhandles[allhandles.length - 1]);
});
like image 42
Jeremy Moritz Avatar answered Jun 02 '26 08:06

Jeremy Moritz