Selenium4 Microsoft Edge WebDriver unable to attach to existing webview2

mnxl 20 Reputation points
2024-04-22T01:10:21.18+00:00

Hi, I am using Selenium Edge webdriver to connect to my existing WebView2 instance(already set system variable on my local machine for remote-debugging-port for the webview2 before webview2 launch) launched by my Windows application, and am receiving the error below:

selenium.common.exceptions.WebDriverException: Message: disconnected: not connected to DevTools (failed to check if window was closed: disconnected: not connected to DevTools) (Session info: MicrosoftEdge=123.0.2420.97)

User's image

import selenium
import subprocess
from selenium import webdriver
from selenium.webdriver.edge.options import Options as EdgeOptions

def run_cmd(cmd, **kwargs):
    try:
        return subprocess.run(f'cmd /c "{cmd}"', **kwargs)
    except Exception as e:
        print(f"Failed to run command:\n{cmd}")
        raise


def terminate_process(process_name):
    run_cmd(f'taskkill /IM "{process_name}" /F')
    
#Terminate all ms edge browsers
for app in ["msedge.exe"]:
    terminate_process(app)

    
edge_options = EdgeOptions()
edge_options.binary_location = r"C:\Program Files (x86)\Microsoft\EdgeWebView\Application\123.0.2420.97\msedge.exe"
edge_options.debugger_address = "localhost:9222"
edge_options.use_webview = True
edge_driver = webdriver.Edge(options=edge_options)  #throws error here
print(edge_driver.page_source)   #does not print 

Microsoft Edge
Microsoft Edge
A Microsoft cross-platform web browser that provides privacy, learning, and accessibility tools.
2,167 questions
{count} votes

Accepted answer
  1. ShiJieLi-MSFT 8,026 Reputation points Microsoft Vendor
    2024-04-22T07:13:37.5666667+00:00

    Hi @mnxl ,

    The snippet you shared works well for me. For this particular error, you may need to add these command lines:

    edge_options.add_argument("--disable-dev-shm-usage")

    edge_options.add_argument("--no-sandbox")

    You can also try other ports if the error is still thrown.

    For the browser version WebView2 app is using, just use print(edge_driver.capabilities['browserVersion']) to check the version, and then use a compatible Edge driver for it.

    UPDATE

    I have reproduced this issue. The cause is another WebView2 app has already been launched prior to this app that is meant to be connected to. For example, Outlook desktop app uses WebView2 component, so if I launched Outlook desktop app before my own WebView2 app, the driver will not be able to connect to my own app.

    2 solutions to this problem:

    1. Prevent any WebView2 app being launched before your target app.
    2. (Recommended) Don't set the environment variable globally (in the system settings). Set the environment variable only for your target application.

    To set the environment variable per-app, following example is for reference

                var options = new CoreWebView2EnvironmentOptions();
                options.AdditionalBrowserArguments = "--remote-debugging-port=9222";
                var env = await CoreWebView2Environment.CreateAsync(null, null, options);
                await webView.EnsureCoreWebView2Async(env);
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    Shijie Li


1 additional answer

Sort by: Most helpful
  1. mnxl 20 Reputation points
    2024-04-25T14:23:10.81+00:00

    Hi @ShiJieLi-MSFT ! Sorry to bother you again, how do I use the driver manager to get the compatible version of msedgedriver for the webview2 edge browser? Our webview2 is using the evergreen installer that auto-updates the edge browser, so I don't wish to hardcode the driver path. I tried 2 ways below, but both are throwing the error:

    selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to microsoft edge at localhost:9222 from session not created: This version of Microsoft Edge WebDriver only supports Microsoft Edge version 124 Current browser version is 123.0.2420.97

                var edgeOptions = new EdgeOptions();
                edgeOptions.UseWebView = true;
                edgeOptions.DebuggerAddress = "localhost:9224";
                edgeOptions.AddArgument("--no-sandbox");
                edgeOptions.AddArgument("--disable-dev-shm-usage");
                string edgeDriverDirectory = @"C:\Users\admin\Downloads\edgedriver_win64\msedgedriver.exe";
    
                //Tried creating service for EdgeDriver
                //EdgeDriverService service = EdgeDriverService();
                // service.DriverServicePath = @"C:\Users\admin\Downloads\edgedriver_win64\msedgedriver.exe";
    
                //Tried using CreateDefaultService()
                //EdgeDriver edgeDriver = new EdgeDriver(EdgeDriverService.CreateDefaultSesrvice("C:\\Users\\admin\\Downloads\\edgedriver_win64", "msedgedriver.exe"));
    
                EdgeDriver edgeDriver = new EdgeDriver(edgeOptions);
    
    0 comments No comments