Reputation: 4430
I want to open a new tab and close the first one in Selenium.
So, I was using the SendKeys
method to do this.
But my problem is when I open the new tab, I can't continue using the SendKeys
method to switch to my first tab and close the current one.
When entering the while loop, both SendKeys
and ExecuteJS
are not working.
I tried using this javascript code:
browser.ExecuteJS("window.close();");
but it is also not working.
My code is like this:
IWebElement body = browser.FindElementByTagName("body");
//browser.ExecuteJS("window.open();");
body.SendKeys(OpenQA.Selenium.Keys.Control + 't');
browser.DeleteAllCookies();
Thread.Sleep(50);
while (browser.GetWindowNum() > 1)
{
body.SendKeys(OpenQA.Selenium.Keys.Control + OpenQA.Selenium.Keys.Tab);
body.SendKeys(OpenQA.Selenium.Keys.Control + 'w');
//browser.ExecuteJS("window.close();");
_tmExcute = DateTime.Now;
}
browser.GoToUrl(link);
browser.WaitForPageToLoad();
I use the method GetWindowNum()
to check if the number of tabs is more than 1.
Here is my code to check the number of tabs in the browser:
public int GetWindowNum()
{
return wd.WindowHandles.Count;
}
Upvotes: 1
Views: 759
Reputation: 31858
You can simply switch the first window and close it using the driver and WindowHandles
ReadOnlyCollection<string> windowHandles = wd.WindowHandles;
string firstWindow = windowHandles.ElementAt(0); //first window handle at 0 index
foreach (string handle in windowHandles) { //Gets the new window handle
if(handle == firstWindow) {
wd.switchTo().window(handle); // switch focus of WebDriver to the first window
wd.close(); //close that window
break;
}
}
Upvotes: 2