Search code examples
webview2

Struggling to grasp WebView2


I've been messing around trying to learn this framework for a job for one week but I couldn't understand yet its pipeline, and how it is working. I delved into every tutorial on the internet, they are very few though. But I couldn't find a tutorial that explains it upon a basic example walking me through. It contains a lot of boilerplate code. Could you provide a simple application of how it works and demystify it step by step?


Solution

  • Working through Microsoft's basic-intro tutorial here will teach you a lot. Don't just read, do! Choose the GUI and language platform you're most familiar with from among WinForms, WPF, and a couple of others.

    Keep in mind that WebView2, like CEF and CEFSharp before it, is a bridge between two vast and different computing paradigms, Windows Native and Chromium browser. And of course there's a third paradigm, web server programming, out there too. WebView2 only involves the first two, but it's important to keep them straight in your mind as you program this stuff. The complexity of the bridge is unavoidable, but you can start with simplicity.

    You don't have to worry overmuch about the process model. The big thing to keep in mind is that WebView2 creates its browser processes the first time your Windows program navigates to a web page or calls EnsureCoreWebView2Async. Thereafter you share a single set of browser processes among all your embedded controls. (You can arrange for multiple sets of browser processes, but don't do that until you really need to.)

    Start by embedding a simple browser control in your Windows app. Get it to display something like https://html5test.com to convince yourself it's working correctly.

    Once you've mastered the basic embedding, you can move on to more complex tasks.

    You can invoke Javascript in the embedded web page, like this.

    You can write C# or C++ code that can be called from Javascript.That's called a HostObject.

    There's another quirk to watch out for. The WebView2 class wraps an inner class called CoreWebView2. Some host-to-browser operations and events use the former, and some the latter. As I learn this, I rely on Visual Studio's code-completion pop ups to figure out what's where.

    For example setting the webView2.Source property does the same thing as calling the webView2.CoreWebView2.Navigate() function. Why? Something to do with wrapped COM objects, but you don't need to completely understand that to do useful things.

    You'll get a taste of all that from the Getting Started samples from Microsoft.

    It has to be said: I admire Microsoft for their belated but very strong commitment to making the native and browser computing environments work together. The old WebView control was as much of a botch job as the late unlamented Internet Explorer browser it embedded.