How to handle internet connection in MAUI WebView

kamlakar khanapure 0 Reputation points
2024-01-04T10:01:22.7866667+00:00

I have created MAUI app with webview. In webview I am call website url. If the interconnection is lost I want to show message internet connection is lost.

MainPage.xaml

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MauiApp2" 
             x:Class="MauiApp2.MainPage"
             BackgroundColor="{DynamicResource PageBackgroundColor}">

   

    <WebView x:Name="webview" BackgroundColor="Transparent"   
                HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
                IsVisible="True"
            
             Source="https://microsoft.com"></WebView>

</ContentPage>
	
Developer technologies | .NET | .NET MAUI
{count} votes

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2024-01-05T02:37:13.4966667+00:00

    Hello,

    MAUI officially provides a way to detect connectivity.

    You could use the following code to alert users when the network is limited or when they lose connection.

    //Add this line of code to the page's constructor
    Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
    
    void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
    {
        if (e.NetworkAccess == NetworkAccess.ConstrainedInternet)
            DisplayAlert("Warning", "Internet access is available but is limited.", "OK");
    
        else if (e.NetworkAccess != NetworkAccess.Internet)
            DisplayAlert("Warning", "Internet access has been lost.", "OK");
    }
    

    Please refer to the Connectivity for more information.

    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.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.