Search code examples
c#seleniumfirefoxgeckodriverselenium-firefoxdriver

How can I attach FirefoxDriver to a running instance of Firefox?


I have started firefox with the argument --start-debugger-server 61300.

FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.AddAdditionalCapability("debuggerAddress", "127.0.0.1:61300");

var d = new FirefoxDriver(firefoxOptions);

d.Navigate().GoToUrl("https://google.com/");

How can I attach the driver to the running instance of firefox so I can jump in and out of controlling it as needed instead of starting a new instance with a random port every time?


Solution

  • After testing, I found a method that works. Using the Selenium.WebDriver.GeckoDriver.Win64 nuget package by jsakamoto.

    I run firefox using the command line:

    "C:\Program Files\Mozilla Firefox\firefox.exe" --marionette -foreground -no-remote

    Then I create the default service and connect using the port 2828 which is the documented default port for marionette.

    FirefoxOptions firefoxOptions = new FirefoxOptions();
    
    FirefoxDriverService firefoxDriverService = FirefoxDriverService.CreateDefaultService();
    firefoxDriverService.HideCommandPromptWindow = false;
    firefoxDriverService.BrowserCommunicationPort = 2828;
    firefoxDriverService.ConnectToRunningBrowser = true;
    
    var driver = new FirefoxDriver(firefoxDriverService, firefoxOptions);
    
    driver.Navigate().GoToUrl("https://youtube.com/");
    

    If there is already an instance of geckodriver running and connected, it will need to be closed first.