Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebView2 initialization in headless mode not work when is invoked by windows service #3458

Open
fabioDG89 opened this issue May 5, 2023 · 7 comments
Assignees
Labels
bug Something isn't working

Comments

@fabioDG89
Copy link

fabioDG89 commented May 5, 2023

Hi,
i'm trying to use WebView2 in headless mode to export in pdf a page but when is invoked by a Windows Service doesn't work.

This is the scenario.

I have a web application named "WebAppService" in ASP.NET Core 6.0. running an html page.

var options = new WebApplicationOptions() {
    Args = args,
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};

var builder = WebApplication.CreateBuilder(options);

builder.Services.AddControllers();

if (!Debugger.IsAttached) {
    builder.Host.UseWindowsService();
}

var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });


app.Run("http://localhost:5000");

In the HTML page there is a button and on click is called a web API that execute the console application used for the initialization of WebView2 and the export in pdf.

[Route("[controller]")]
    public class ExportWebViewController:Controller {

        [HttpGet("ExecProcess")]
        public ActionResult ExecProcess() {
            Process.Start("C:\\Sources\\WebView2Headless\\ConsoleApp1\\bin\\Debug\\net6.0-windows\\ConsoleApp1.exe");
            return Ok();
        }
    }

The executable invoked "ConsoleApp1" contains the methods to initialize WebView2 in headless mode, navigate and export in pdf.

static void CreateWebView2() {
    System.Diagnostics.Debugger.Launch();
    CoreWebView2Controller browserController;
    string WEBVIEW2_RUNTIME_FOLDER = @"C:\Sources\WebView2Headless\ConsoleApp1\bin\Debug\WebView2Runtime.110.0.1587.63.x64";
    IntPtr HWND_MESSAGE = new IntPtr(-3);
    var uiThread = new Thread(() => {

        Dispatcher.CurrentDispatcher.Invoke(async () => {
            var environment = await CoreWebView2Environment.CreateAsync(WEBVIEW2_RUNTIME_FOLDER, null, null);

            browserController = await environment.CreateCoreWebView2ControllerAsync(HWND_MESSAGE);
            browserController.CoreWebView2.NavigationCompleted += NavigationComplete;

            browserController.CoreWebView2.Navigate("https://developer.microsoft.com/it-it/microsoft-edge/webview2/");

        });

        Dispatcher.Run();
    });

    uiThread.SetApartmentState(ApartmentState.STA);
    uiThread.Start();
    uiThread.Join();

    void NavigationComplete(object sender, CoreWebView2NavigationCompletedEventArgs args) {
        browserController.CoreWebView2.PrintToPdfAsync(@"C:\Temp\ExportFromWebView2.pdf");
        Console.WriteLine("Export complete!");
    }
}


[STAThread]
static void Main(string[] args) {
    Console.WriteLine("START -> CreateWebView2 Environment...");
    CreateWebView2();
}

Main(args);

When the web application "WebAppService" is running in debug mode in Visual Studio (or invoked by a Console Application), the export works.

When the web application is invoked by a Windows Service, the export doesn't work: the "ConsoleApplication1" is executed, but it stucks at method "CreateCoreWebView2ControllerAsync" (no exceptions are returned).

I'm using WebView2Runtime.110.0.1587.63.x64

Thanks for your help!

Fabio

@fabioDG89 fabioDG89 added the bug Something isn't working label May 5, 2023
@fabioDG89 fabioDG89 changed the title WebView2 initialization in headless mode not work when in invoked by windows service WebView2 initialization in headless mode not work when is invoked by windows service May 5, 2023
@LiangTheDev
Copy link
Member

Could this be related to #1907? That's an unsupported scenario.

@fabioDG89
Copy link
Author

No, in my scenario the windows service run under a user that is administrator

@LiangTheDev
Copy link
Member

Then that could be due to difficulty to create non elevated WebView2 processes. WebView2 processes cannot run elevated. For normal session, we create non elevated WebView2 processes through explorer. I would imagine that it doesn't work when running in windows service. So, this is a scenario that we do not support currently.

@fabioDG89
Copy link
Author

To avoid misunderstandings I explain my scenario:

This is the windows service that start the web application in ASP.NET Core 6.0.

01

It is executed by the user "ServiceExecutor", that is local administrator:

02

Clicking on the button Export, it calls the action "ExecProcess" that execute the console application "ConsoleApp1.exe" that initialize WebView2 in headless mode, navigate and export in pdf.

03

The process started by the user "ServiceExecutor", but nothing it is exported.

04

This scenario could be supported?

Thanks for support!

@LiangTheDev
Copy link
Member

LiangTheDev commented May 10, 2023

This is a setup WebView2 has not been tested with, and therefore not officially supported.

In the setup, ConsoleApp1.exe is running elevated and as different user, probably in an invisible session. We have several hurdles to overcome: launch de-elevated WebView2 process, which depends on explorer, allow the launched WebView2 process running as different user (the same interactive user as explorer) to access connection end point created by the elevated process, and Chromium's sandbox code works in this invisible session.

That being said, WebView2 code might have already overcome the first 2 hurdles and it is the Chromium's sandbox code that is preventing it from working. You could try to create WebView with --no-sandbox additional browser arguments (CoreWebView2Environment.CreateAsync(WEBVIEW2_RUNTIME_FOLDER, null, new CoreWebView2EnvironmentOptions("--no-sandbox"));) and see whether it works.

If it doesn't work, it is the first 2 hurdles that is breaking the scenario. Try to use latest version of Edge WebView2 runtime and see whether it works. We made some changes related to elevated app in Edge 112, which might or might not help. If still does not work, could you try to config it to run as a non admin user?

@fabioDG89
Copy link
Author

I try your suggestions and it works when the Windows Service run with a user that is NOT administrator.
So isn't there a way to make it work with an admin user?

@LiangTheDev
Copy link
Member

If it works with non admin but not with admin even using --no-sandbox, it means that dependency on explorer is the one that prevents it from working. Therefore, it is a WebView2 limitation with no workaround. Running the service with non admin account is the only workaround.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants