Jeremy Ragsdale
Jeremy Ragsdale

Reputation: 25

.net Maui WebView.EvaluateJavaScriptAsync return data from JavaScript callback

I have a .net WPF app where I am using a WebView2 control to render a node.js app. The node.js app is fairly simple and contains a few async functions that call out to a rest API and using a callback waits for the results. Currently I use window.chrome.webview.postMessage to send the results back to the WebView2 and the messageReceived event. I also have a few buttons on the WPF app that call out to the web app to execute some JS.

I am looking to build a cross platform app using .net MAUI and I see that there is a WebView control and that is has the same ability to execute JS on the web app using eval & WebView.EvaluateJavaScriptAsync but I don’t see a way to post\receive a message with the WebView?

The docs kind of eludes to using a JS callback to send the data from the web app to the MAUI app but I can’t seem to grasp how that would work?

Here is an example of one of the JS functions. MyLib.get cards is a 3rd party function that makes a call to another platform and retrieves a list of cards.

function getCards(){
   Mylib.getCards(function(resp){
     return resp;
   });
} 

I can call this using WebView.EvaluateJavaScriptAsync but I am not understanding how to get the results back into the MAUI app

string result = await webView.EvaluateJavaScriptAsync($"getCards()");

Previously I just use the postMessage capability to post the results to the WebView2 when they returned from the callback.

Can someone please tell me, is this possible and if so how to make it work.

Upvotes: 1

Views: 2968

Answers (3)

Stephen Quan
Stephen Quan

Reputation: 26214

As a workaround we can make use of document.title as follows:

function getCards(){
   Mylib.getCards(function(resp){
     document.title = JSON.stringify(resp);
   });
}

Then, in C# we run EvaluateJavaScriptAsync() twice, i.e.

await webView.EvaluateJavaScriptAsync($"getCards()");
await Task.Delay(1000); // allow getCards() to run to completion
string result = webView.EvaluateJavaScriptAsync("document.title");

Upvotes: 1

Kevin
Kevin

Reputation: 135

This is what I use in my MAUI app to read the value of a Label called hiddenkey on my webpage

    var Key = await Browser.EvaluateJavaScriptAsync($"document.getElementById('hiddenkey').innerHTML");

Upvotes: 0

Zack
Zack

Reputation: 1629

In MAUI you can send requests to the web service with the HttpClient Class.

For more details, you can refer to the following docs: Consume a REST-based web service | Microsoft Docs

Upvotes: 0

Related Questions