How to load *.html and corresponding *.js files and css from folder in WebView2 control in C# WPF application

Ajay Gera 0 Reputation points
2024-08-01T17:27:23.87+00:00

Hi,

I have set of *.html files (a.html , b.html , c.html), *.js files (say 1a.js , 2b.js, 3b.js) and one css file in local folder in my windows machine,

I need to start loading these files in webview2 control (in wpf .net framework application) starting with a.html which uses 1a.js file and later on some action need to load another file say 2.html which invokes set of JavaScript files e.g. say 2b.js and 3b.js.

We also need to populate UI by making some http calls.

What is the recommended approach to solve this issue?

Please share the sample code as well.

Can I use Virtual host name mapping basically CoreWebView2.SetVirtualHostNameToFolderMapping Method . Will it handle all scenarios I mentioned above?

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,908 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,671 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 51,586 Reputation points
    2024-08-01T17:38:55.3233333+00:00

    Yes that is what that method is for. You define a host name (e.g. localassets.example and then the folder to map it to. When the control sees the URL (e.g. https://localassets.example/index.htm) then it loads the corresponding file from the folder you gave instead of making a call via the INet. In theory you can do this for any file since all it does is change where the file is being delivered from.

    The docs have the best example of how to do this. But here's a quick example. Assume the hostedfiles folder contains index.htm, index.js and image.png files. Configure the host mapping that you need.

    webView.CoreWebView2.SetVirtualHostNameToFolderMapping("localassets.example", "hostedfiles", CoreWebView2HostResourceAccessKind.Allow);
    

    Finally in the index.htm file.

    <!DOCTYPE html>
    <html>
       <head>
          <Title>Local Site</Title>
       </head>
       <body>
          <img src="https://localassets.example/image.png" />
          <script src="https://localassets.example/index.js"></script>
       </body>
    </html>
    
    0 comments No comments