In my WPF application, I am successfully able to communicate a message from WPF to JavaScript using the InvokeScript(String, Object[]) method of WebBrowser. I am passing my message in Object[] parameter and it is well received by JS code. (See the code below)
How can I achieve the same thing in WebView2? Is there any way we can pass on the parameters to the JS Code just like we do in WebBrowser control?
Window.xaml
<Grid>
<DockPanel>
<StackPanel>
<TextBox x:Name="txtMessageFromWPF" Width="150" FontSize="20"></TextBox>
<Button x:Name="btnCallDocument" Click="btnCallDocument_Click" Content="CallDocument" />
</StackPanel>
<WebBrowser x:Name="webBrowser" DockPanel.Dock="Top" Margin="30"/>
</DockPanel>
</Grid>
Window.xaml.cs
private void btnCallDocument_Click(object sender, RoutedEventArgs e)
{
webBrowser.InvokeScript("WriteMessageFromWPF", new object[] { this.txtMessageFromWPF.Text });
}
JS Code:
<script type="text/javascript">
function getAlert()
{
alert("Hi the page is loaded!!!");
}
window.onload = getAlert;
function WriteMessageFromWPF(message){
document.write("Message from WPF: " + message);
}
</script>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With