Search code examples
javascriptseleniumcoffeescript

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?


Solution

  • var parent = driver.getWindowHandle();
    var windows = driver.getAllWindowHandles();
    
    driver.switchTo().window(windows[1]);
    
    // do some stuff
    
    driver.close();
    driver.switchTo().window(parent);