Home > Back-end >  Change WebView URL source at runtime
Change WebView URL source at runtime

Time:01-17

I want to change MAUI .NET Webview Source at runtime.

I have this code, which is summoned by a button in XAML

C# CODE:

void OnReloadWebView(object sender, EventArgs e)
{  
   try
   {
        WebView = new WebView();
        WebView.Source = new UrlWebViewSource
        {
            Url = "https://blog.xamarin.com/"
        };
        WebView.Reload();
   }
   catch (Exception ex)
   {
     Debug.WriteLine(ex.Message);
   }
}

XAML TAG

<StackLayout Margin="10">
        <Button Clicked="OnReloadWebView" Text="Recargar"></Button>
        <ProgressBar Progress ="0.1" HorizontalOptions="FillAndExpand" x:Name="progress"/>
        <WebView x:Name="WebView" VerticalOptions="FillAndExpand"  
                     Navigating="WebView_OnNavigating"
                     Navigated="WebView_OnNavigated"/>
</StackLayout>

Does anyone know if this is possible?

I was expecting for the Webview to reload and change the URL but nothing happened not even seems to be reloading.

CodePudding user response:

this works for me

wv.Source = new UrlWebViewSource() { Url = "http://www.google.com" };

CodePudding user response:

First of all, you should change x:Name="WebView" to something like x:Name="MyWebView", because having an object and a class with the same name is confusing:

<StackLayout Margin="10">
    <Button Clicked="OnReloadWebView" Text="Recargar"></Button>
    <ProgressBar Progress ="0.1" HorizontalOptions="FillAndExpand" x:Name="progress"/>
    <WebView x:Name="MyWebView" VerticalOptions="FillAndExpand"
             WidthRequest=300
             HeightRequest=300 
             Navigating="WebView_OnNavigating"
             Navigated="WebView_OnNavigated"/>
</StackLayout>

You also need to specify a WidthRequest and a HeightRequest explicitly as per the official documentation:

A WebView must specify its HeightRequest and WidthRequest properties when contained in a HorizontalStackLayout, StackLayout, or VerticalStackLayout. If you fail to specify these properties, the WebView will not render.

Then, in your code behind you're making the mistake that you're assigning a new WebView instance to the field, which you previously also called WebView (now changed to MyWebView). Instead if doing that, remove the instantiation:

void OnReloadWebView(object sender, EventArgs e)
{  
   try
   {
       WebView.Source = new UrlWebViewSource
       {
           Url = "https://blog.xamarin.com/"
       };
   }
   catch (Exception ex)
   {
     Debug.WriteLine(ex.Message);
   }
}

There should also be no need to call Reload(), because assigning a new URL should automatically load the new page.

  • Related