简体   繁体   中英

Can't send keys in Selenium C#

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;
}

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM