Update: Version 2 of the extension is much simpler and more universal. It uses JSON as 'middle-station'- use NewtonSoft or the built-in JSON converter.
Here's an extension I have made (just create a class file and paste it).
The ExecuteScriptFunctionAsync
builds the string necessary for ExecuteScriptAsync
and then executes it:
//using Microsoft.Web.WebView2.WinForms; //Uncomment the one you use
//using Microsoft.Web.WebView2.Wpf; //Uncomment the one you use
using Newtonsoft.Json;
using System.Threading.Tasks;
public static class Extensions
{
public static async Task<string> ExecuteScriptFunctionAsync(this WebView2 webView2, string functionName, params object[] parameters)
{
string script = functionName + "(";
for (int i = 0; i < parameters.Length; i++)
{
script += JsonConvert.SerializeObject(parameters[i]);
if (i < parameters.Length - 1)
{
script += ", ";
}
}
script += ");";
return await webView2.ExecuteScriptAsync(script);
}
}
Pass the javascript function name as first parameter, followed by the function parameters.
The code makes it possible to have any number of parameters of all types that can be srialized to JSON: object
, array
, string
, all numbers
, boolean
etc.
Example of use (from the question):
private async void btnCallDocument_Click(object sender, RoutedEventArgs e)
{
await webBrowser.ExecuteScriptFunctionAsync("WriteMessageFromWPF", this.txtMessageFromWPF.Text);
}
Another example (this will scroll the window to bottom):
await webView21.ExecuteScriptFunctionAsync("window.scrollTo", 0, 10000);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…