Search code examples
.netxamlmauimaui-windows

Change WebView URL source at runtime


I want to change the Source of a .NET MAUI WebView at runtime.

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

Code behind

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

<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.


Solution

  • 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.

    Alternatively, you could place the WebView inside a Grid, then you won't need to request the width and height.

    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
       {
           MyWebView.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.