Check with Selenium if browser is open

1.8k views Asked by At

I'm using C# / Selenium 3 and the Microsoft Chromium Edge Webdriver to scrape a web page and then deliver data to another application. I need to check if the user has closed the web browser. Is there a quick way of doing this? I came up with the code below but the problem is that if the web browser is closed then _webDriver.CurrentWindowHandle takes 4 seconds or more before it throws an exception.

public bool IsOpen
{
    get
    {
        if (!this._isDisposed)
        {
            try
            {
                _ = this._webDriver.CurrentWindowHandle;
                return true;
            }
            catch
            {
                // ignore.
            }
        }

        return false;
    }
}
2

There are 2 answers

1
making On BEST ANSWER

In the end I came up with the following solution: I used the extension method (shown below ) to get a .Net Process object for the Web Browser. To check if the browser is still open I just check the property process.HasExited. If this is true then the user has closed the browser. This method does not call Selenium so even if the browser is closed the result is near instant.

/// <summary>
/// Get the Web Drivers Browser process.
/// </summary>
/// <param name="webDriver">Instance of <see cref="IWebDriver"/>.</param>
/// <returns>The <see cref="Process"/> object for the Web Browser.</returns>
public static Process GetWebBrowserProcess(this IWebDriver webDriver)
{
    // store the old browser window title and give it a unique title.
    string oldTitle = webDriver.Title;
    string newTitle = $"{Guid.NewGuid():n}";

    IJavaScriptExecutor js = (IJavaScriptExecutor)webDriver;
    js.ExecuteScript($"document.title = '{newTitle}'");

    // find the process that contains the unique title.
    Process process = Process.GetProcesses().First(p => p.MainWindowTitle.Contains(newTitle));

    // reset the browser window title.
    js.ExecuteScript($"document.title = '{oldTitle}'");
    return process;
}
1
Yu Zhou On

It takes seconds to throw an exception because when the browser is closed, the driver will still retry to connect to the browser. It can't tell if the browser is closed by manually or automatically.

I need to check if the user has closed the web browser

Automation browser test shouldn't be interrupted by manual intervention. It's against all the best practices. If you close the browser manually, WebDriver will throw WebDriverException. So, you can also use try-catch method on WebDriverException to check if the browser is reachable. But it will also take seconds to throw an exception with the same reason as the above.

If you want to prevent users to close the browser manually, you can use Edge in headless mode like below:

edgeOptions.AddArguments("--headless");