Laszlo
Laszlo

Reputation: 2328

Change focus to another window, where name is undefined

I'm using WD.js webdriver client for node.js to test my app.

In my app after a button click a new browser window opens. Obviously by the nature of selenium the old window stays active.

I've tried to use the window() method from wd.js to switch to the new window but it needs a window name as a parameter which isn't set.

Is there any way to switch between windows without knowing their name?

Upvotes: 1

Views: 4713

Answers (3)

adiwon
adiwon

Reputation: 59

I used this and it worked for all browsers:- Try this code:-

var tab_handles =await driver.getAllWindowHandles();
let number_of_tabs = tab_handles.length;
let new_tab_index = number_of_tabs-1;
await driver.switchTo().window(tab_handles[new_tab_index]); 

That was using await instead of Promise for async functions.

If you want to use Promise then try this code:-

driver.getAllWindowHandles().then((tab_handles)=>{
let number_of_tabs = tab_handles.length;
let new_tab_index = number_of_tabs-1;
driver.switchTo().window(tab_handles[new_tab_index]);
});

Hope it helps....

Upvotes: 1

chrismillah
chrismillah

Reputation: 3914

foo, i found the answer to this.

you will want to use this function here

var handlePromise = driver.getAllWindowHandles();
handlePromise.then(function (handles){
  var popUpWindow = handles[1];

  driver.switchTo().window(popUpWindow);
})
  1. here we are telling the driver to get all window handles
  2. we then are passing the handles as a parameter to our function
  3. we then are assigning the value of handles[1] (which is the new window) to the variable 'popUpWindow'
  4. telling driver to switch to that new window

Upvotes: 2

Karthikeyan
Karthikeyan

Reputation: 2732

I would do the following in java implementation ,

  String parentWindowHandle = browser.getWindowHandle(); // save the current window handle.
  WebDriver popup = null;
  Iterator<String> windowIterator = browser.getWindowHandles();
  while(windowIterator.hasNext()) { 
    String windowHandle = windowIterator.next(); 
    popup = browser.switchTo().window(windowHandle);
    if (popup.getTitle().equals("Google") {
      break;
    }
  }

Here, the name is not mandatory. Similarly, can you try to loop over and switch ? For your information,

 switchToWindow(name/Handle) 

- Switch focus to a different browser window by name or handle. So try this and let the community know the solution. Good luck !

Upvotes: -1

Related Questions