How to switch tabs in Selenium without focusing the window

I'm using the C# Selenium and Edge webdriver on Windows 10. Below is my code for switch between tab.

public class BrowserTest
{
    private readonly EdgeDriver driver;
    public BrowserTest()
    {
        EdgeDriverService service = EdgeDriverService.CreateDefaultService(configuration[DriverPathKey]);
        service.SuppressInitialDiagnosticInformation = true;
        service.HideCommandPromptWindow = true;
        driver = new EdgeDriver(service, new EdgeOptions()
        {
            PageLoadStrategy = PageLoadStrategy.Default,
        });
    }

    public void OpenGoogleAndDuckduckgo()
    {
        driver.Url = "https://google.com/";
        driver.ExecuteScript("window.open();");
        driver.SwitchTo().Window(driver.WindowHandles.Last()); // This line lead to Edge focusing
        driver.Url = "https://duckduckgo.com/";
    }
}

But seem it focusing Edge browser that taking me away from checking my e-mail or etc. How can I get Selenium to "silently" focus on a new tab (or window etc) so I can do something while my code runs?

P/s: I tried for headless mode but I need to manual input credentials to login so I need a UI. Or if there a way to turn from window mode to headless mode in runtime?

Upvotes: 0

Views: 826

Answers (2)

cruisepandey
cruisepandey

Reputation: 29382

I think you should use the same code but consider deploying your script in VM. with that you can continue to do your stuff in your local wherein your selenium code will get executed in Virtual machine (With your own OS setup )

Oracle VM virtual Box provides very feasible solution with respect to virtual machines. Check out their official web sites linked. They have different distribution for MacOS, Linux and Windows operating system.

Upvotes: 1

mojmir.novak
mojmir.novak

Reputation: 3439

  1. You can not achieve that (change focus without focus) in Selenium. If you are running Selenium tests, just use different machine. HW or virtual.

Headless mode of browser is not a good solution also. Sooner or later you will have too much problems to solve with differences between normal mode and headless mode.

  1. Avoiding captcha is very hard in automation mode of browser. You need AI to solve captcha in that mode and it is even not guaranteed it will works (depends on captcha and server protection). If you need to test or grab some pages which has this protection you have to use different approach: Write addon for browser (javascript app) and run it in regular mode of browser.

Upvotes: 2

Related Questions