0

Is it possible to retrieve the HTML a .NET MAUI WebView is currently displaying?
If so, how?
Unfortunately, I can't find anything on it inside the official documentation.

.NET MAUI WebView documentation

I am trying to retrieve the currently displayed HTML as a string, after a JavaScript event changed the HTML body content, to read out some meta-data.

Dokug
  • 123
  • 8

2 Answers2

1

I don't think you can access it directly (like with WebView2). However you can call Javascript, which have access to the HTML :

string result = await webView.EvaluateJavaScriptAsync($"document.documentElement.innerHTML");
Poulpynator
  • 716
  • 5
  • 13
0

You may use Navigated event to detect if page changes:

In .xaml,

<WebView x:Name="webview" ... Navigated="webview_Navigated" />

In .cs, implement Event Handler

async void webview_Navigated(System.Object sender, Xamarin.Forms.WebNavigatedEventArgs e)
{
    var webView = sender as WebView;
    HttpClient client = new HttpClient();
    // Get the html
    var html = await client.GetStringAsync((webView.Source as UrlWebViewSource).Url);
    }

Furthermore, you may want JS/C# interaction on MAUI WebView. You could refer to this SO issue: JS/.NET interact on MAUI WebView.

Hope it works for you.

Liqun Shen-MSFT
  • 3,490
  • 2
  • 3
  • 11
  • Thanks, I'll try the tip with the HttpClient. Unfortunately, WebView does not register the Navigated event on most javascript interactions that are relevant for me. But I think I'll find a workaround for that. – Dokug Feb 11 '23 at 07:14
  • If you find a workaround, you could share your solution as an answer if possible. That may help others with same issue. – Liqun Shen-MSFT Feb 13 '23 at 02:21
  • I will definitely do that, I haven't come around to trying out the suggestions unfortunately. – Dokug Feb 14 '23 at 09:17
  • Navigated event only detect different pages load and that's not for JavaScript interactions. I also google this for native but also in vain. Probably Maui WebView cannot detect JavaScript change for an uncustomized webpage. – Liqun Shen-MSFT Feb 15 '23 at 07:02