Hello,
You can use Handler to solve this problem. Please refer to the following code example:
We create a CustomWebViewClient
class and set it to platformWebView
.
public DailyReadingPage()
{
InitializeComponent();
ModifyWebView();
...
CallDailyReading(htmldata);
}
void ModifyWebView()
{
Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
{
#if ANDROID
if (handler.PlatformView is global::Android.Webkit.WebView platformWebView)
{
platformWebView.SetWebViewClient(new CustomWebViewClient(this.mywebview));
}
#endif
});
}
Here is the code for CustomWebViewClient
class, you can place it just in code behind,
#if ANDROID
public class CustomWebViewClient : WebViewClient
{
Microsoft.Maui.Controls.WebView mywebview;
public CustomWebViewClient(Microsoft.Maui.Controls.WebView webView)
{
mywebview = webView;
//mywebview.HeightRequest = 0;
}
public async override void OnPageFinished(Android.Webkit.WebView view, string url)
{
mywebview.HeightRequest = 0;
await Task.Delay(500); // Allow time for content to load
string js = "document.body.scrollHeight";
var height = await mywebview.EvaluateJavaScriptAsync(js);
if (double.TryParse(height, out double newHeight) && newHeight > 0)
{
mywebview.HeightRequest = newHeight; // Set WebView height dynamically
}
base.OnPageFinished(view, url);
}
}
#endif
Just set the height: 100%
is okay.
It will adjust the size then.
By the way, though it seems not necessary, you could also try adding the PropertyChanged
event for the WebView and implement it. The code is shown below for your reference, hope it helps!
<WebView PropertyChanged="mywebview_PropertyChanged"
x:Name="mywebview"
and implement it in code behind,
private void mywebview_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
#if ANDROID
if (e.PropertyName == "Source")
{
if (this.mywebview.Handler != null)
(this.mywebview.Handler.PlatformView as Android.Webkit.WebView).SetWebViewClient(new CustomWebViewClient(this.mywebview));
}
#endif
}
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.