Embed Web Technologies (html, javaScript) into WPF Applications Using WebVeiw2 | Part 1

Embed Web Technologies (html, javaScript) into WPF Applications Using WebVeiw2 | Part 1

In one of my current project at work, I'm faced with the task of integrating Azure Communication Services video call feature into a WPF application. However, as of May 5th, 2024, there hasn't been an Azure Communication Service Client SDK for WPF. Consequently, I've opted to develop a separate communication module using JavaScript and then incorporate it into the WPF application via WebView2.

This article will guide you through simulating JavaScript events in a WPF environment and retrieving the outcomes.

Microsoft Edge WebView2

  • The Microsoft Edge WebView2 control offers a way to incorporate web technologies like HTML, CSS, and JavaScript into our native .NET applications.
  • WebView2 in WPF allows seamless integration of web content with C# code, offering a powerful toolset for developers.
  • The WebView2 control uses Microsoft Edge as the rendering engine to display the web content in native apps.
  • For further details, please refer to the webView2 Microsoft Documentation

A sample project that demonstrating how to use the WebView2 control in a WPF application to display a simple web page.

Project Proposal

image - web application

I'm planning to create a basic web application using HTML and JavaScript. The app will utilize a public API to fetch country data. Users will input a country name into a text box, then click a search button to retrieve the country's data. The application will display the country's flag as a result.

image - WPF web hybrid application

In my WPF native application, I intend to simulate filling the country name text box and clicking the search button. After that, I'll retrieve the country's population and display it in a WPF message box.

Project Development

  • You can view the full project on GitHub at GitHub repository link
  • In readme file you can find how to find keys for the API.

1. Create Web Application

Here, I've highlighted the important parts of the code for our developments

in .html page <body>

   <input type="text" id="txt-country-input" placeholder="Enter a country">        
 <button id="btn-search" type="button">Search</button>        
<div id="flag-container"></div>        

in .js page

// UI widgets
let countryName = document.getElementById("txt-country-input");
let searchButton = document.getElementById("btn-search");        
searchButton.addEventListener('click', async () => {
    const country = countryName.value.trim();
    await getCountryData(country);
});        

getCountryData(country) function you can see in the provided git hub repository.

2. Create WPF Application

  • Create WPF Application
  • Install WebView2 NuGet package to the solution.

image - NuGet package

  • Add Webview2 to the application.

in .xaml file

xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"        
<wv2:WebView2 Name="webView" Grid.Column="1" Margin="2"/>        

  • Load webpage to the WebView component.

in .xaml.cs file we can load the web page to the webView2 component.

 public string url = @""; // Add your hosted URL here        
 // Ensure that the CoreWebView2 environment is initialized asynchronously
 await webView.EnsureCoreWebView2Async(null);

 // Navigate the CoreWebView2 instance to the specified URL
 webView.CoreWebView2.Navigate(url);        

Simulate web page From WPF

case 1 :

Mirror WPF textbox input on the web page textbox

image - mirror WPF textbox on web page textbox

Here, we can use this kind of approach. We can use the TextChanged event to capture the textbox value, and then inside that function, write code to mirror the textbox value on the web page textbox.

in WPF,

<!-- text box -->
<TextBox x:Name="TxtCountryName"  TextChanged="TxtCountryName_TextChanged" />        
private  void TxtCountryName_TextChanged(object sender, TextChangedEventArgs e)
{
    // Execute JavaScript to set the value of the web text box to the WPF text box value
}        

With ExecuteScriptAsync() we can execute JavaScript code directly from our WPF application, enabling dynamic interaction between the web view JavaScript and our C# logic trough webView.


webView.CoreWebView2.ExecuteScriptAsync("JavaScript code here"); can use.

In our case that JavaScript code is,

document.getElementById('txt-country-input').value = '{TxtCountryName.Text.Trim()}')        

Below code shows the event that can be used.

private async void TxtCountryName_TextChanged(object sender, TextChangedEventArgs e)
{
    await webView.CoreWebView2.ExecuteScriptAsync($"document.getElementById('txt-country-input').value = '{TxtCountryName.Text.Trim()}';");
}        

case 2 :

Simulate web page button click() from WPF button click()

image - simulate web page button click from WPF button click

We can simulate a button click in a web view using a simple code line with ExecuteScriptAsync().

In web view,

searchButton.addEventListener('click', async () => {
    //business logic here 
});        

We can call it from WPF,

private async void BtnSearch_Click(object sender, RoutedEventArgs e)
{
    await webView.CoreWebView2.ExecuteScriptAsync("document.getElementById('btn-search').click();");
}        
image - simulate web page button click from WPF button click - example result


Get Messages from web view to WPF

We can easily receive messages from a web view in WPF by using the postMessage() function in JavaScript. Let's do it.

In the web view, we are going to post a simple message. It's better to have a message template. Here, we are using a simple data message, so we are using the "key": "value" format to POST the message."

In web view (JavaScript),

As an example, if we want to retrieve population data from the web view, we can use

 window.chrome.webview.postMessage(`population: ${population}`);        

In WPF,

We can capture that data and show it in a Popup message.

First, we have to subscribe a method to listen to the incoming message. If a message comes, then it can proceed.

webView.CoreWebView2.WebMessageReceived += WebView_WebMessageReceived;        
private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
   //busines logic here
}        

In our case, first, we have to split up the incoming message. Then, we can access the messages and decide what to do.

string message = args.TryGetWebMessageAsString();

// Incoming message format => "key : value"
string[] messageArray = message.Split(':');        
 if (messageArray.Length == 2)
 {
     string key = messageArray[0];
     string value = messageArray[1];

     if (key == "population")
     {
         MessageBox.Show($"{TxtCountryName.Text.Trim()} : {key} is {value}");
     }
 }        
image - Message box showing incoming message information in WPF


As you can see, if you use WebView2, you can directly communicate with a web page without using websockets or other technologies.

I hope you could gain a small knowledge about WebView2. These examples are completely made up, but in real-time scenarios, these basics can make your work very easy.

Thank you.

Chandrasekhar Peddineni

Software Developer | Problem Solving | Cloud Computing | Full Stack Developer

4 个月

Does this WebView2 supports IE mode? If not are there any modern libraries to embed web technologies into WPF application which supports IE mode

回复
Tharindu R.

Quality Assurance Engineer at Paymedia

4 个月

Insightful!

要查看或添加评论,请登录

Bhathiya Bandara的更多文章

社区洞察

其他会员也浏览了