Search code examples
c#microsoft-edgeselenium-edgedriverselenium3

Check with Selenium if browser is open


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

Solution

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