Home > Enterprise >  WebView2 in Winui 3: CORS errors when loading an Ionic/Angular application from the local file syste
WebView2 in Winui 3: CORS errors when loading an Ionic/Angular application from the local file syste

Time:01-01

Following on from my last post, 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.

The relevant code here is

await MyWebView.EnsureCoreWebView2Async();
MyWebView.CoreWebView2.Navigate("file:///D:/0/www/index.html"); // test while waiting how to load from Assets
//MyWebView.CoreWebView2.Navigate("ms-appx-web:///www/index.html");
MyWebView.CoreWebView2.OpenDevToolsWindow();

When I run it, in dev tools, I get the following CORS errors when it is trying to load the js files within the index.html

        Access to script at 'file:///D:/0/www/runtime.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
    runtime.js:1 
                    
                 Failed to load resource: net::ERR_FAILED
    index.html:1 
                    
                 Access to script at 'file:///D:/0/www/polyfills.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
    polyfills.js:1 
                    
                 Failed to load resource: net::ERR_FAILED
    index.html:1 
                    
                 Access to script at 'file:///D:/0/www/vendor.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
    vendor.js:1 
                    
                 Failed to load resource: net::ERR_FAILED
    index.html:1 
                    
                 Access to script at 'file:///D:/0/www/main.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
    main.js:1 
                    
                 Failed to load resource: net::ERR_FAILED

Is there some way I can get around this?

CodePudding user response:

Looks like the solution to my other issue also solved this one.

Need to use SetVirtualHostNameToFolderMapping

 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