How to attach a Selenium ChromeDriver to an embedded CefSharp browser in a WPF application?

Viewed 1420

I have a ChromiumWebBrowser control in my MainWindow.xaml:

<cefSharp:ChromiumWebBrowser x:Name="chromiumBrowser" Address="https://www.github.com/"/>

and I'm trying to drive it by attaching a Selenium ChromeDriver to it:

    ChromeOptions options = new ChromeOptions();
    options.BinaryLocation = AppDomain.CurrentDomain.FriendlyName;
    options.AddArguments("disable-extensions");
    options.AddArguments("disable-plugins");

    ChromeDriver chromeDriver = new ChromeDriver(options);
    chromeDriver.Url = "http://www.reddit.com";

Is this a correct approach? It seems to nearly work as the embedded control flashes once when the driver attempts to connect to it but then I get the following error from the ChromeDriver console:

[1006/220430.356:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5) [1006/220430.357:ERROR:cache_util.cc(139)] Unable to move cache folder GPUCache to old_GPUCache_000

EDIT

Apparently attaching a driver using options.BinaryLocation will unfortunately always launch a new instance of the executable. From the comments below, I gathered that the correct way would be to attach the driver through a debug port. So I create my browser control through code:

CefSettings settings = new CefSettings();
settings.RemoteDebuggingPort = 9222;
settings.UserDataPath = "C:/Temp";
Cef.Initialize(settings);
browserControl = new ChromiumWebBrowser("chrome://version");

But when I try to attach to it:

    ChromeOptions options = new ChromeOptions();
    options.AddArguments("--remote-debugging-port=9222");

    ChromeDriver driver = new ChromeDriver(options);
    driver.Url = "http://www.reddit.com";

The error is now: System.InvalidOperationException: 'session not created from disconnected: unable to connect to renderer (Session info: chrome=85.0.4183.121) (SessionNotCreated)'

This could be due to mismatching chrome versions as CefSharp only supports up to v84 at the moment. I'm using a v84 chromedriver so I don't know where this 85 warning comes from.

1 Answers

After sustaining some massive hair loss, I found out that this works:

CefSettings settings = new CefSettings();
settings.RemoteDebuggingPort = 9222;
settings.UserDataPath = "C:/Temp";
Cef.Initialize(settings);
browserControl = new ChromiumWebBrowser("chrome://version");

And this is how to gloriously attach to the embedded ChromiumWebBrowser:

ChromeOptions options = new ChromeOptions();
options.DebuggerAddress = "localhost:9222";

ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;

ChromeDriver driver = new ChromeDriver(service, options);

The trick was to use ChromeOptions.DebuggerAddress instead of ChromeOptions.AddArguments("--remote-debugging-port=XXXX")

Related