Maxime Joyal
Maxime Joyal

Reputation: 183

how to know the PID for the browser used by a selenium IWebDriver?

I need to know the process ID of the browser (or tab if google chrome) which execute the IWebDriver GoToUrl method.

I found this on stack overflow: Find PID of browser process launched by Selenium WebDriver

However, my browser is already opened. For the worse case, if it's google chrome, I need the process ID of the tab which went on the URL.

Reason

I use Fiddler to capture requests, and when I capture the requests, I can access the process ID. I need to match it with browser which did the GoToUrl.

Upvotes: 1

Views: 2396

Answers (1)

Sean Griffin
Sean Griffin

Reputation: 171

If you ran the code that executed IWebDriver to start the Chrome browser then you can add more code that will get the PID for you.

You don't state which language you are using. Below is an example you can use for C# and Selenium. There would be the same implementation for other languages (like Java) but I am only working in C#.

Chrome allows you to supply your own user-defined command-line arguments. So you can add an argument named "scriptpid-" with the PID (Windows Process ID) of your currently running program. ChromeDriver passes your argument to Chrome in the command-line. Then using Windows WMI calls retrieve this PID from the command-line of the running Chrome ...

public static IntPtr CurrentBrowserHwnd = IntPtr.Zero;
public static int CurrentBrowserPID = -1;
        
ChromeOptions options = new ChromeOptions();
options.AddArgument("scriptpid-" + System.Diagnostics.Process.GetCurrentProcess().Id);
IWebDriver driver = new ChromeDriver(options);

// Get the PID and HWND details for a chrome browser

System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("chrome");
for (int p = 0; p < processes.Length; p++)
{
    ManagementObjectSearcher commandLineSearcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + processes[p].Id);
    String commandLine = "";
    foreach (ManagementObject commandLineObject in commandLineSearcher.Get())
    {
        commandLine += (String)commandLineObject["CommandLine"];
    }

    String script_pid_str = (new Regex("--scriptpid-(.+?) ")).Match(commandLine).Groups[1].Value;

    if (!script_pid_str.Equals("") && Convert.ToInt32(script_pid_str).Equals(System.Diagnostics.Process.GetCurrentProcess().Id))
    {
        CurrentBrowserPID = processes[p].Id;
        CurrentBrowserHwnd = processes[p].MainWindowHandle;
        break;
    }
}

CurrentBrowserHwnd should contain the HWND of your Chrome window.

CurrentBrowserPID should contain the Process ID of your Chrome window.

Upvotes: 1

Related Questions