Embed Web Technologies (html, javaScript) into WPF Applications Using WebVeiw2 | Part 1
Bhathiya Bandara
Associate Software Engineer Desktop Applications (.NET | WPF) | .NET Core | Laravel |Crafting Real-World Solutions | Blogger
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
A sample project that demonstrating how to use the WebView2 control in a WPF application to display a simple web page.
Project Proposal
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.
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
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
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"/>
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
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()
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();");
}
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}");
}
}
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.
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
Quality Assurance Engineer at Paymedia
4 个月Insightful!