Home > Enterprise >  WebView2 in Winui 3: How to load a local HTML file nested within the application
WebView2 in Winui 3: How to load a local HTML file nested within the application

Time:01-01

I am looking for a way to wrap my Ionic/Angular application with some sort of Windows application. I am looking at Electron (and having issues), but also investigating if I just created my own WinUI3 application and used Webview2.

Though this is Ionic/Angular, I think this would apply to any local HTML file.

I can get it to load if I use an absolute reference to the HTML file, eg

MyWebView.CoreWebView2.Navigate("file:///D:/0/www/index.html");

(I then get CORS errors, but I have a separate post for that)

But, I want my files to be embedded within the application, eg add a www folder under assets, and I then try MyWebView.CoreWebView2.Navigate("ms-appx-web:///www/index.html");, but I get the following error:

Failed to launch 'ms-appx-web:///www/index.html' because the scheme does not have a registered handler.

Here is my sample app:

    namespace WinUI3_1
    {
        /// <summary>
        /// An empty window that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainWindow : Window
        {
            public MainWindow()
            {
                this.InitializeComponent();
                try
                {
                    //MyWebView.Source = new Uri("ms-appx-web:///assets/www/index.html");
                    Init();        
                }
                catch (Exception ex)
                {       
                    int i = 0;
                }     
            }

            private async void Init()
            {
                try
                {
                    await MyWebView.EnsureCoreWebView2Async();
                    MyWebView.CoreWebView2.Navigate("file:///D:/0/www/index.html");
                    //MyWebView.CoreWebView2.Navigate("ms-appx-web:///www/index.html");
                    MyWebView.CoreWebView2.OpenDevToolsWindow();
                }
                catch (Exception)
                {
                    int i = 0;
                }      
            }   
        }
    }

How can I reference the file locally as I am trying above?

CodePudding user response:

I found a way that seems to at least load the application.

Looking at this post and this documentation, I could do the following...

 await MyWebView.EnsureCoreWebView2Async();

 MyWebView.CoreWebView2.SetVirtualHostNameToFolderMapping(
     "appassets", "assets", CoreWebView2HostResourceAccessKind.Allow);
    
 MyWebView.Source = new Uri("http://appassets/www/index.html");
 MyWebView.CoreWebView2.OpenDevToolsWindow();

This now found the index.html and also loaded it with no CORS issues.

  • Related